【问题标题】:Tkinter using append to print to a labelTkinter 使用 append 打印到标签
【发布时间】:2018-12-25 21:20:27
【问题描述】:

我一直在尝试返回函数printLabel 以打印“Hello 世界!”,但我不太确定如何进一步发展:

我想使用lambda,以便在单击按钮时在标签中打印我的附加字符串,但这会在没有单击按钮的情况下显示。我的 代码如下:

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()

【问题讨论】:

  • 打印的lambda函数可以是lambda x: print(x)

标签: python button tkinter label


【解决方案1】:

我对你的代码做了一些修改,它应该可以按照你想要的方式工作:

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()

【讨论】:

  • 按照建议完成后,这将不会打印到标签而是打印到控制台,请问这附近有吗?
  • 我在viewingPanel中添加了这个:text="{}".format(self.printLabel())),但我希望它在我点击按钮时出现,而不是在GUI显示时执行。
  • @pythonnewbie 感谢您告诉我,编辑了我的答案。让我知道进一步的变化。
  • 感谢您的解决方案,这就是我希望我的 GUI 的样子。
猜你喜欢
  • 1970-01-01
  • 2014-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-22
  • 2015-06-06
相关资源
最近更新 更多