Python:从旋转框中读取数字,并执行以下命令之一



早上好/晚上好,

我想从旋转框中读取一个数字,如果是2,它应该会打印一些东西。但是我的代码不起作用。我试过用滑块而不是旋转框,结果成功了。但对我来说,使用spinbox真的很重要,所以我希望有人能有个主意。

代码:

from tkinter import *
def a():
if spin.get()==2:
print("Hello World")
root = Tk()
root.geometry('300x100')
spin =Spinbox(root, from_=0, to=10,command=a)
button = Button(root, text='Enter')
button.pack(side=RIGHT)
spin.pack(side=RIGHT)
root.mainloop()

在@coolCloud的回答中,我建议为spinBox设置一个文本变量。因此,如果用户使用条目进行更改。它将自动更新。

类似这样的东西:

from tkinter import *
def a(*event):
if text.get()=='2':
print("Hello World")
root = Tk()
root.geometry('300x100')
text = StringVar()
text.trace('w', a) # or give command=a in the button if you want it to call the event handler only when the button is pressed
spin =Spinbox(root, from_=0, to=10, textvariable=text)
button = Button(root, text='Enter')
button.pack(side=RIGHT)
spin.pack(side=RIGHT)
root.mainloop()

最新更新