Tkinter - 从spinbox获取值

7

我目前遇到了从“spinbox”部件获取正确值的困难,不知道出了什么问题。我已经搜索了解决方案,但是一无所获。我做错了什么?以下是我的代码:

from Tkinter import *

#create Tk window
root = Tk()

#set name of window
root.title('Testing Values')

#initalise values from user (spinbox values)
item_1 = IntVar()
a = item_1.get()

def print_item_values():
    global a
    print a


#item 1 spinbox
item_1 = Spinbox(root, from_= 0, to = 10, width = 5)
item_1.grid(row = 0, column = 0)

#print values
value_button = Button(root, text = 'Print values', width = 10, command = print_item_values)
value_button.grid(row = 0, column = 1)


root.mainloop()
2个回答

6
在你的代码中,a 从未被更新。相反,要获取 spinbox 的值,只需使用其 .get() 方法:
item_1 = Spinbox(root, from_= 0, to = 10, width = 5)
item_1.grid(row = 0, column = 0)

def print_item_values():
    print item_1.get()

Tkinter Spinbox 文档


2
您可以在您的代码中进行以下更改。
from tkinter import *

root = Tk()

root.title('Testing Values')

item_1 = IntVar()

def print_item_values():
    a = item_1.get()
    print(a)

item_1 = Spinbox(root, from_= 0, to = 10, width = 5)
item_1.grid(row = 0, column = 0)

value_button = Button(root, text = 'Print values', width = 10, command = 
print_item_values)
value_button.grid(row = 0, column = 1)

root.mainloop()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接