Tkinter 按钮绑定
这是我的代码:
import Tkinter
from Tkconstants import *
tk = Tkinter.Tk()
class MyApp:
def __init__(self,parent):
self.frame = Tkinter.Frame(tk,relief=RIDGE,borderwidth=2)
self.frame.pack()
self.message = Tkinter.Message(tk,text="Symbol Disolay")
label=Tkinter.Label(self.frame,text="Is Symbol Displayed")
label.pack()
self.button1=Tkinter.Button(self.frame,text="YES")
self.button1.pack(side=BOTTOM)
self.button1.bind("<Button-1>", self.button1Click)
self.button2=Tkinter.Button(self.frame,text="NO")
self.button2.pack()
self.button2.bind("<Button-1>", self.button2Click)
def button1Click(self, event):
"pressed yes"
def button2Click(self, event):
"pressed no"
myapp = MyApp(tk)
tk.mainloop()
我应该在button1Click()和button2Click()中做什么,以便它们以字符串格式向我的程序返回“YES”或“NO”?
This is my code:
import Tkinter
from Tkconstants import *
tk = Tkinter.Tk()
class MyApp:
def __init__(self,parent):
self.frame = Tkinter.Frame(tk,relief=RIDGE,borderwidth=2)
self.frame.pack()
self.message = Tkinter.Message(tk,text="Symbol Disolay")
label=Tkinter.Label(self.frame,text="Is Symbol Displayed")
label.pack()
self.button1=Tkinter.Button(self.frame,text="YES")
self.button1.pack(side=BOTTOM)
self.button1.bind("<Button-1>", self.button1Click)
self.button2=Tkinter.Button(self.frame,text="NO")
self.button2.pack()
self.button2.bind("<Button-1>", self.button2Click)
def button1Click(self, event):
"pressed yes"
def button2Click(self, event):
"pressed no"
myapp = MyApp(tk)
tk.mainloop()
What shall I do in button1Click() and button2Click() so that they return "YES" or "NO" to my program in string format?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法“返回”字符串,因为回调是从事件循环中调用的,并且事件循环会忽略从回调返回的所有值,因为它不知道如何处理返回的值。
如果您希望将“是”或“否”应用于 self.message 小部件,您可以将回调更改为如下所示:
然后,您需要使消息小部件可见。 例如,在代码中的某处添加“self.message.pack()”。
如果您需要更具体的问题答案,您需要更好地描述“返回”的含义 - 您是否想要查看标签中的文本、出现在弹出对话框中等。
You can't "return" a string, because the callbacks are called from the event loop and the event loop ignores all values returned from callbacks since it doesn't have any knowledge of what to do with the returned values.
If you want "YES" or "NO" to be applied to the self.message widget, you can change your callbacks to look like this:
You'll then need to make the message widget visible. For example, add "self.message.pack()" in your code somewhere.
If you need a more specific answer to your question you'll need to do a better job of describing what you mean by "return" -- do you want to see the text in a label, appear in a popup dialog, etc.
只需
return "pressed yes"
即可将字符串返回给 TKinter 处理程序,TKinter 处理程序将忽略它。您必须在点击定义中执行某些操作,例如更新标签文本
simply
return "pressed yes"
will return the string to the TKinter handler, which'll ignore it.You have to do something in your click defs, e.g. update the label text