[英]How to get each tkinter Entry's unique value from loop
I'm trying to create a hangman game which produces a random amount of entries.我正在尝试创建一个产生随机数量条目的刽子手游戏。 Problem is, I can't get the unique value of each entry.问题是,我无法获得每个条目的唯一值。
This is what I have tried so far:这是我到目前为止所尝试的:
from tkinter import *
import random
root = Tk()
root.geometry('500x500')
color = 'blue'
a1 = Canvas(root, height = 500, width = 500, bg = color)
a1.pack()
#Variable Declaration
var = StringVar()
x = ''
words = ['penguin','wolves','skyscraper','dinosaur','time travel']
lists = {}
def Enter():
for i in lists:print(lists[i])
x = 'entry'
a=150
b=350
for i in range(len(random.choice(words))):
lists[f'entry{i}'] = Entry(textvariable = StringVar(),width =3, font = 'tahoma',justify=CENTER).place(x=a,y=b)
a+=30
b1 = Button(root, text = "Enter",command=Enter)
b1.place(x=225,y=400)
root.mainloop()
In your case I would advice the make 1 input field for text and split the letter later.在您的情况下,我建议将文本输入字段设为 make 1,然后再拆分字母。 A string in python can be accessed like a list, you have len(string) and string[3] gives the 4 letter ect. python 中的字符串可以像列表一样访问,你有 len(string) 和 string[3] 给出 4 个字母等。
The first thing you must do is separate the creation of the widget from the layout of the widget.您必须做的第一件事是将小部件的创建与小部件的布局分开。 In python, x().y()
returns the value of y()
, so Entry(...).place(...)
returns the value of place(...)
and place(...)
always returns None
.在 python 中, x().y()
返回y()
() 的值,因此Entry(...).place(...)
...) 总是返回place(...)
和place(...)
的值返回None
。
The second thing I would do is not use f'entry{i}'
for the index into your lists.我要做的第二件事是不要使用f'entry{i}'
作为列表的索引。 It will work, but it's more cumbersome than it needs to be.它会起作用,但它比它需要的更麻烦。
for i in range(len(random.choice(words))):
lists[i] = Entry(textvariable = StringVar(),width =3, font = 'tahoma',justify=CENTER)
lists[i].place(x=a,y=b)
a+=30
The above lets you easily reference any entry widget with something like lists[0]
, lists[1]
, etc.上面的内容让您可以轻松地引用任何条目小部件,例如lists[0]
、 lists[1]
等。
Finally, in your Enter
method (which should be named enter
according to PEP8 guidelines), you can directly loop over the entries without using the index at all:最后,在您的Enter
方法中(根据PEP8指南应命名为enter
),您可以直接遍历条目而不使用索引:
def Enter():
for index, entry in lists.items():
value = entry.get()
print(value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.