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()