Python:Tkinter 确定按钮回调函数
我正在做我的第一个Python图形界面(GUI),想要修改这个tkinter示例,但是我就是搞不懂怎么为“确定”按钮写一个回调函数,让它把输入的值传递给主程序。
#!/usr/bin/python
# -*- coding: utf-8 -*-
from Tkinter import Tk, BOTH, StringVar, IntVar
from ttk import Frame, Button, Style, Label, Entry
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Get Value")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
valueLabel = Label(self, text="Value: ")
valueLabel.place(x=10, y=10)
value=StringVar(None)
value.set("this is the default value")
valueEntry=Entry(self, textvariable=value)
valueEntry.place(x=70, y=10)
quitButton = Button(self, text="Quit", command=self.quit)
quitButton.place(x=10, y=50)
okButton = Button(self, text="OK", command=self.quit)
okButton.place(x=120, y=50)
def main():
root = Tk()
root.geometry("220x100+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
我看了很多教程,但没有一个能清楚地解释这个问题。理论上,我应该能用value.get()来获取选中的值,但无论我把它放在哪里,总是会出现错误信息。而且,按照我所知道的,我应该能用value.set()来定义一个默认值,但这似乎没有效果,因为我运行程序时文本框是空的。
在root.mainloop()结束后,最简单的方式是什么来把值传递给主Python程序?(实际的对话框里有几个输入框,用来输入字符串和整数值。)
也就是说,我想能用类似这样的方式:
root = Tk() root.geometry("220x100+300+300") app = Example(root) root.mainloop() print value print value2 print value3
我怎么定义输入框的默认值?
2 个回答
0
你的 quitButton 和 okButton 都在调用 self.quit 函数。所以无论你在按下 OK 按钮时输入什么值,实际上都是在调用 quit 函数,这样会引发一些其他问题,这些问题不在你提问的范围内。
试着把值定义为 self.value,然后让 okButton 调用一个函数,这个函数的作用是:打印出 self.value.get() 的内容。
2
把所有出现的 value
变量都换成 self.value
。这样应该就能解决问题,默认值就会显示出来。
更新
from Tkinter import Tk, BOTH, StringVar, IntVar
from ttk import Frame, Button, Style, Label, Entry
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def showMe(self):
print(self.value.get())
def initUI(self):
self.parent.title("Get Value")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
valueLabel = Label(self, text="Value: ")
valueLabel.place(x=10, y=10)
self.value=StringVar(None)
self.value.set("this is the default value")
valueEntry=Entry(self, textvariable=self.value)
valueEntry.place(x=70, y=10)
quitButton = Button(self, text="Quit", command=self.quit)
quitButton.place(x=10, y=50)
okButton = Button(self, text="OK", command=self.showMe)
okButton.place(x=120, y=50)
def main():
root = Tk()
root.geometry("220x100+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()