来自条目的Tkinter .get()给出了奇怪的值

时间:2016-03-14 23:50:04

标签: python tkinter

我有一个使用Tinter和Turtle的简单GUI程序,其目标是绘制多边形。我向用户询问边数和边长。我做了一个简单的GUI,但当我点击按钮获取值时,我得到非常小的十进制数值,我无法弄清楚原因。

import Tkinter as tk

def draw_polygon():
    num_of_sides.get()
    length_of_sides.get()

    print num_of_sides, length_of_sides

root = tk.Tk()

tk.Label(root, text='Number of Sides').grid(row=0)
tk.Label(root, text='Length of Sides').grid(row=1)

num_of_sides = tk.Entry(root)
num_of_sides.grid(row=0, column=1)

length_of_sides = tk.Entry(root)
length_of_sides.grid(row=1, column=1)

draw_button = tk.Button(root, text='Draw', command=draw_polygon)
draw_button.grid(row=3, column=1)

tk.mainloop()

1 个答案:

答案 0 :(得分:2)

您必须将get()的返回值分配给变量。否则,您打印窗口小部件的名称,默认情况下是一个点后跟一个数字。

import Tkinter as tk

root = tk.Tk()

tk.Label(root, text='Number of Sides').grid(row=0)
tk.Label(root, text='Length of Sides').grid(row=1)

num_of_sides = tk.Entry(root, name = "numOfSides")
num_of_sides.grid(row=0, column=1)

length_of_sides = tk.Entry(root, name = "lenOfSides")
length_of_sides.grid(row=1, column=1)

def draw_polygon():
    ns = num_of_sides.get()
    ls = length_of_sides.get()

    print ns, ls                
    print num_of_sides, length_of_sides

draw_button = tk.Button(root, text='Draw', command=draw_polygon)
draw_button.grid(row=3, column=1)

tk.mainloop()

当然,您可以评论或删除第二个print,我将其留待解释。您也可以删除两个name=参数。