python 从顶部输入框更新标签文本

3b6akqbq  于 5个月前  发布在  Python
关注(0)|答案(1)|浏览(79)
from tkinter import *

root = Tk()
root.title('change text')
Label1 = Label(root, text = 'Change me')
Label1.pack()

def presto():
     Label1.configure(text = entry1.get())

def open_sub():
     top1 = Toplevel(root)
     top1.title('Buttons')
     label1 = Label(top1, text = 'Type Something')
     entry1 = Entry(top1, width = 20)
     button1 = Button(top1, text = "execute", command = presto)
     button2 = Button(top1, text = 'close', command = top1.destroy)
     label1.pack()
     entry1.pack()
     button1.pack()
     button2.pack()

 button1 = Button(root, text = 'page 2', command = open_sub)
 button1.pack()

 root.mainloop()

字符串
这个程序目前的工作方式是创建一个根窗口,标签上写着“改变我”,还有一个打开顶层窗口的按钮,顶层窗口中有一个标签,标签上写着“键入一些东西”。然后是一个输入框和一个执行按钮和关闭按钮。当按下执行按钮时,它应该将根窗口上标签中的文本更改为输入小部件中键入的任何内容。但我得到了错误代码:

Exception in Tkinter callback
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.11/tkinter/__init__.py", line 1948, in __call__
        return self.func(*args)
           ^^^^^^^^^^^^^^^^
File "/storage/emulated/0/Documents/Pydroid3/Character Generator/anothermain.py", line 9, in presto
    Label1.configure(entry1.get())
                            ^^^^^^
NameError: name 'entry1' is not defined

uurity8g

uurity8g1#

您可以将输入文本传递给presto()

def presto(text):
    Label1.configure(text=text)

def open_sub():
    ...
    button1 = Button(top1, text="execute", command=lambda: presto(entry1.get()))
    ...

字符串

相关问题