Tkinter-从微调框获取值

2024-04-24 11:36:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前无法从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()

Tags: fromvalue部件columnbuttonrootwindowitem
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()

在您的代码中,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 Documentation

相关问题 更多 >