python-3.x Tkinter孩子的窗口按钮来更改列表框的内容

pw136qt2  于 2023-06-25  发布在  Python
关注(0)|答案(2)|浏览(164)

我有一个带有标签和按钮的toplevel(子)窗口。button命令连接到一个更改child的窗口标签文本的函数。我得到了一个“undefined name...”作为子窗口标签的名称。我是Python和tkinter的新手,我相信这是非常简单的事情。我会很感激任何人能给予我任何建议。

import tkinter as tk
root = tk.Tk()
root.geometry("300x300")
root.title("Root")

def child(): #Create child window
    child = tk.Toplevel()
    child.geometry("350x350+100+100")
    child.title("Child Window")
    
    lb1 = tk.Label(child, text = "Child Label")
    lb1.pack()
    
    Cbtn = tk.Button(child, text = "Change Child Label text", command = cLabelChange)
    Cbtn.pack()

def cLabelChange():
    lb1.configure(text = "I changed this text") #THIS IS WHERE THE ERROR OCCURS

btn = tk.Button(root, text = "Open Child.", command = child)
btn.pack()

root.mainloop()

我到处都找过了,但什么也没有。也许我的问题措辞不正确。

mrzz3bfm

mrzz3bfm1#

tkinter子窗口按钮来改变列表框的内容
这个问题是可以解决的。

  • cLabelChange()函数移动到child()函数内部。
  • cLabelChange()函数的Cbtnpack移动到底部。

仅此而已
片段:

import tkinter as tk
root = tk.Tk()
root.title("Root")
root.geometry("300x300")
 

def child(): #Create child window
    child = tk.Toplevel()
    child.title("Child Window")
    child.geometry("350x350+100+100")
         
    lb1 = tk.Label(child, text = "Child Label")
    lb1.pack()
         
    def cLabelChange():
        lb1.configure(text = "I changed this text") #THIS IS WHERE THE ERROR OCCURS
        child.update()

    Cbtn = tk.Button(child, text = "Change Child Label text", command = cLabelChange)
    Cbtn.pack()    

btn = tk.Button(root, text = "Open Child.", command = child)
btn.pack()

root.mainloop()

截图:

vmdwslir

vmdwslir2#

这可能是您的问题的替代解决方案。将lb1作为参数传递给labelChange()函数,这样就可以在函数内部访问标签小部件,如下所示。要做到这一点,你必须使用lambda函数传递参数。

import tkinter as tk
root = tk.Tk()
root.geometry("300x300")
root.title("Root")

def child(): #Create child window
    child = tk.Toplevel()
    child.geometry("350x350+100+100")
    child.title("Child Window")
    
    lb1 = tk.Label(child, text = "Child Label")
    lb1.pack()
    
    Cbtn = tk.Button(child, text = "Change Child Label text", command = lambda:cLabelChange(lb1))
    Cbtn.pack()

def cLabelChange(lb1):
    lb1.configure(text = "I changed this text") #THIS IS WHERE THE ERROR OCCURS

btn = tk.Button(root, text = "Open Child.", command = child)
btn.pack()

root.mainloop()

相关问题