简体   繁体   English

tkinter中的用户输入是否存储为“条目”而不是“ int”?

[英]User inputs in tkinter are stored as 'Entry' instead of 'int'?

I'm using tkinter to obtain a list of x and y coordinates from the user. 我正在使用tkinter从用户那里获取x和y坐标的列表。 An initial pop up obtains the number of coordinates and then creates a pop up with the correct number of input boxes. 初始弹出窗口获取坐标数,然后创建带有正确数量的输入框的弹出窗口。

xcoord = []
ycoord = []
x = []
y = []

for i in range(numofcoordiantes):
    xcoord[i] = ttk.Entry(mainframe, textvariable=x[i])
    ycoord[i] = ttk.Entry(mainframe, textvariable=y[i])

ttk.Button(mainframe, text="OK", command=lambda: function(xcoord, ycoord))

However, when I try to do the calculations I get the error: 但是,当我尝试进行计算时,出现错误:

TypeError: unsupported operand type(s) for -: 'Entry' and 'int' TypeError:-:“ Entry”和“ int”的不受支持的操作数类型

If I print out the coordiantes they look like this: 如果我打印出coordiantes,它们看起来像这样:

[<tkinter.ttk.Entry object at 0x03EDF9B0>, <tkinter.ttk.Entry object at 0x03EDFA30>, <tkinter.ttk.Entry object at 0x03EDFAB0>]
[<tkinter.ttk.Entry object at 0x03EDF9D0>, <tkinter.ttk.Entry object at 0x03EDFA50>, <tkinter.ttk.Entry object at 0x03EDFAD0>]

None of my other input boxes give me this issue, so I'm not sure if this is a result of using a list. 我的其他输入框都没有给我这个问题,所以我不确定这是否是使用列表的结果。 If so, could you please point me in an alternate direction? 如果是这样,您能指出我的另一个方向吗?

You are storing references to the entry widgets in xcoord and ycoord , rather than the values of the entry widgets. 您将在xcoordycoord中存储对条目小部件的ycoord ,而不是条目小部件的值。 You can remove the use of textvariable and get the values from the entry widgets like this: 您可以删除textvariable的使用,并从条目小部件中获取值,如下所示:

x_coordinates = [int(widget.get()) for widget in xcoord]
y_coordinates = [int(widget.get()) for widget in ycoord]

Though, you'll get errors if any of the widgets are blank or have non-integers in them. 但是,如果任何窗口小部件为空白或其中包含非整数,都会出现错误。 You'll have to add some error handling code to take care of that. 您必须添加一些错误处理代码来解决这一问题。

If you are unfamiliar with list comprehensions, the first line of code above is simply shorthand for this: 如果您不熟悉列表推导,则上面的第一行代码只是此的简写形式:

x_coordinates = []
for widget in xcoord:            # for each widget in the list...
    s = widget.get()             # get string value
    value = int(s)               # convert to integer
    x_coordinates.append(value)  # append to the list of coordinates

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM