Python Forum

Full Version: output to canvas widget
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
First post here on this new forum.

I'm trying to get a windows 'dir' command output to display in a canvas widget. Ultimately I want to built an interactive program than will display the output in the canvas widget; this is the first step to get it working.

from Tkinter import *
import subprocess

class window:


   def __init__(self, parent):
       self.frame=Frame(parent)
       self.frame.pack()
       self.gobutton = Button(self.frame, text="Go", command=self.dircall)
       self.gobutton.grid(row=0, column=1)
       self.canvas = Canvas(root, width = 100, height = 100, bg = "white")
       self.canvas.pack()
   def dircall(self):
       output=subprocess.call(["dir", "c:"], shell=True)
       self.canvas.create_text(25, 25, text=output, tags="text")


root = Tk()
root.geometry("200x200")
runit=window(root)
root.mainloop()
When started the GUI opens and then when the button is clicked the output is a 0 and the output from the dir command goes to the run output part of my IDE. I don't get and error, it just doesn't quite do what I want it to.

Any help pointing me to the solution would be appreciated.
"0" means that the "dir"-command was processed successfully.
You could use check_output():


       output=subprocess.check_output(["dir", "c:"], shell=True)
I modified a bit, you'll need a bigger Canvas or a smaller font
from Tkinter import *
# import subprocess
import os

class Window:
    def __init__(self, parent):
        self.frame = Frame(parent)
        self.frame.pack()
        self.gobutton = Button(self.frame, text="Go", command=self.dircall)
        self.gobutton.grid(row=0, column=1)
        self.canvas = Canvas(root, width=100, height=100, bg="white")
        self.canvas.pack()

    def dircall(self):
        # output = subprocess.call(["dir", "c:"], shell=True)
        # self.canvas.create_text(25, 25, text=output, tags="text")
        output = os.listdir('C:/')
        x = 5
        y = 10
        for line in output:
            print(line)
            self.canvas.create_text(x, y, text=line, tags='text', anchor='nw')
            y += 10


root = Tk()
root.geometry("200x200")
runit = Window(root)
root.mainloop()