【发布时间】:2020-08-12 06:47:26
【问题描述】:
具有两个按钮的应用程序可根据用户偏好调用函数
您好,提前感谢您的帮助!我是 tkinter 的相对初学者,并且已经完成了一些教程和堆栈溢出中的一些问题。但是,在用户按下按钮后,我无法在 GUI 窗口中生成回调函数的输出。代码概述如下:
root = tk.Tk()
root.title('Crowdsourcing creativity')
class Application(tk.Frame):
下面我尝试创建一个可以通过退出键退出的全屏应用
def __init__(self, master=None):
super().__init__(master)
self.master = master
pad=3
master.geometry("{0}x{1}+0+0".format(
master.winfo_screenwidth()-pad, master.winfo_screenheight()-pad))
master.bind('<Escape>',self.close_window)
self.pack()
self.create_widgets()
def close_window(self,event):
root.destroy()
接下来我创建了两个按钮
def create_widgets(self):
prompt_button = tk.Button(self,text = 'Do something', command=self.give_prompt).pack(side=tk.LEFT)
location_button = tk.Button(self, text = 'Go somewhere', command=self.give_location).pack(side=tk.RIGHT)
最后我尝试定义按钮的回调函数。注意 prompt() 和 location() 指的是前面代码中定义的函数(本质上是从它们各自的列表中返回一个随机项)。
def give_prompt(self):
label1 = Label(self, prompt())
label1.pack()
def give_location(self):
label2 = Label(self, location())
label2.pack()
app = Application(master=root)
app.mainloop()
输出当前显示在我运行代码的终端中,而不是 GUI。我还希望原始按钮在单击时消失,以便输出是 GUI 中唯一剩下的东西。任何有关如何解决此问题的建议将不胜感激!谢谢
【问题讨论】:
-
快到了。您需要将两个标签创建为
tk.Label,而不仅仅是Label。然后,每个按钮单击都会创建一个新的 tk.Label。 -
感谢@TlsChris!我现在有一个工作应用程序
标签: tkinter