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

3b6akqbq  于 2024-01-05  发布在  Python
关注(0)|答案(1)|浏览(170)
  1. from tkinter import *
  2. root = Tk()
  3. root.title('change text')
  4. Label1 = Label(root, text = 'Change me')
  5. Label1.pack()
  6. def presto():
  7. Label1.configure(text = entry1.get())
  8. def open_sub():
  9. top1 = Toplevel(root)
  10. top1.title('Buttons')
  11. label1 = Label(top1, text = 'Type Something')
  12. entry1 = Entry(top1, width = 20)
  13. button1 = Button(top1, text = "execute", command = presto)
  14. button2 = Button(top1, text = 'close', command = top1.destroy)
  15. label1.pack()
  16. entry1.pack()
  17. button1.pack()
  18. button2.pack()
  19. button1 = Button(root, text = 'page 2', command = open_sub)
  20. button1.pack()
  21. root.mainloop()

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

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

uurity8g

uurity8g1#

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

  1. def presto(text):
  2. Label1.configure(text=text)
  3. def open_sub():
  4. ...
  5. button1 = Button(top1, text="execute", command=lambda: presto(entry1.get()))
  6. ...

字符串

相关问题