简体   繁体   中英

Tkinter using append to print to a label

I have been trying to return the fuction printLabel to print "Hello world!", but I am not too sure how to progress further:

I would like to use lambda in order to print my append strings in the label when the button is clicked but this displays without the button being clicked. My code is as follows:

from tkinter import *

class Example(Frame):   

    def printLabel(self):
        self.hello = []
        self.hello.append('Hello\n')
        self.hello.append('World!')
        print(self.hello)  
        return(self.hello)        

    def __init__(self, root):
        Frame.__init__(self, root)
        self.buttonA()
        self.viewingPanel()

    def buttonA(self):
        self.firstPage = Button(self, text="Print Text", bd=1, anchor=CENTER, height = 13, width = 13, command=lambda: self.printLabel())
        self.firstPage.place(x=0, y=0)        

    def viewingPanel(self):  
        self.panelA = Label(self, bg='white', width=65, height=13, padx=3, pady=3, anchor=CENTER, text="{}".format(self.printLabel()))
        self.panelA.place(x=100, y=0)        


def main():
    root = Tk()
    root.title("Tk")
    root.geometry('565x205')
    app = Example(root)
    app.pack(expand=True, fill=BOTH)
    root.mainloop()

if __name__ == '__main__':
    main()

I made a few modifications to your code, and it should work the way you want:

from tkinter import *

class Example(Frame):  

    def printLabel(self):
        self.hello.append('Hello\n')
        self.hello.append('World!')  
        return(self.hello) 

    # Added 'updatePanel' method which updates the label in every button press.
    def updatePanel(self):
        self.panelA.config(text=str(self.printLabel()))

    # Added 'hello' list and 'panelA' label in the constructor.
    def __init__(self, root):
        self.hello = []
        self.panelA = None
        Frame.__init__(self, root)
        self.buttonA()
        self.viewingPanel()

    # Changed the method to be executed on button press to 'self.updatePanel()'.
    def buttonA(self):
        self.firstPage = Button(self, text="Print Text", bd=1, anchor=CENTER, height = 13, width = 13, command=lambda: self.updatePanel())
        self.firstPage.place(x=0, y=0)        

    # Changed text string to be empty.
    def viewingPanel(self):  
        self.panelA = Label(self, bg='white', width=65, height=13, padx=3, pady=3, anchor=CENTER, text="")
        self.panelA.place(x=100, y=0)        


def main():
    root = Tk()
    root.title("Tk")
    root.geometry('565x205')
    app = Example(root)
    app.pack(expand=True, fill=BOTH)
    root.mainloop()

if __name__ == '__main__':
    main()

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