简体   繁体   中英

How to return string value of Console output to put it into a label in Tkinter

I made a python script that has a lot of print statements showing what the program is doing rather than just having it just sit there and the python script works fine now I am creating a front end with tkinter. What I used to send the print statements to return them is some thing like this:

test.py
def PrintX():
    X = [1,2,3,4,5]
    for x in X:
        print(x)

My plan is to have a tkinter frame in that I put a label and set the text variable to my function in my script. My tkinter page script looks like this so far:

class TradingBotapp(tk.Tk):

    def __init__(self,*args,**kwargs):
        tk.Tk.__init__(self,*args,**kwargs)
        container = tk.Frame(self)
        container.pack(side='top',fill='both',expand= True)
        container.grid_rowconfigure(0,weight = 1)
        container.grid_columnconfigure(0,weight = 1)
        self.frames = {}

        for F in (InitalSetup):
            frame = F(container,self)
            self.frames[F] = frame
            frame.grid(row=0,column=0,sticky='nsew')

        self.show_frame(InitalSetup)

    def show_frame(self,cont):
        frame = self.frames[cont]
        frame.tkraise()

class InitalSetup(tk.Frame):

    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text='Setup', font = LARGE_FONT).pack()
        Frame = tk.Frame(self,width=768,height=576).pack()
        lbl = tk.Message(Frame, text='').pack()
        button1 = ttk.Button(self, text='Start Setup',command=lambda:callback2(lbl)).pack()

def callback2(object):

    old_stdout = sys.stdout
    sys.stdout = StdoutRedirectorLabel(lbl)
    setup()
    #lbl['text'] = sys.stdout.result.strip()
    sys.stdout = old_stdout

class StdoutRedirectorLabel(object):

    def __init__(self,widget):
        self.widget = widget
        self.widget['text'] = ''

    def write(self, text):
        self.widget['text'] += text


app = TradingBotapp()
app.mainloop()

But nothing is showing up, but when I press the button I get self.widget['text'] = '' TypeError: 'NoneType' object does not support item assignment any help would be much appreciated

Haha... You've fallen victim to one of the classic blunders,, (In all seriousness, I've done this many times before, you're not alone) I believe you need to pack your labels with label1.pack() after their creation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM