访问列表中的 Tkinter 小部件时出现问题
我正在尝试使用 Python 和 Tkinter 编写一个小程序,其中有一个标签和条目字段列表(请参见下面的代码)。添加小部件没有问题。但是,当我想使用其中一个实例的方法(例如在一个条目字段上使用 Insert())时,我无法找到一种方法来实现它。
我的代码如下所示:
from Tkinter import *
import random
root = Tk()
attributes = {'Strength':10, 'Dexterity':10, 'Constitution':10, 'Intelligence':10, 'wisdom':10, 'charisma':10}
entries = []
labels = []
i = 0
for a in attributes:
labels.append(Label(root, text = a, justify = LEFT).grid(sticky = W))
entries.append(Entry(root).grid(column = 1, row = i))
i = i+1
root.mainloop()
我尝试了一个简单的
entries[i].insert("text to insert")
但
e = Entry
e = entries[i]
e.insert...
没有帮助。我见过其他人尝试使用列表中的对象的例子,看起来他们只是像我第一次尝试时那样做。我错过了什么吗?
谢谢
I'm trying to write a small program where I have a list of Labels and Entry-fields using Python and Tkinter (see code below). Adding the widgets is no problem. However, when I want to use a method of one of the instances (like Insert() on one of the Entry-fields) I can't figure out a way to do it.
My code looks like this:
from Tkinter import *
import random
root = Tk()
attributes = {'Strength':10, 'Dexterity':10, 'Constitution':10, 'Intelligence':10, 'wisdom':10, 'charisma':10}
entries = []
labels = []
i = 0
for a in attributes:
labels.append(Label(root, text = a, justify = LEFT).grid(sticky = W))
entries.append(Entry(root).grid(column = 1, row = i))
i = i+1
root.mainloop()
and I have tried a simple
entries[i].insert("text to insert")
and
e = Entry
e = entries[i]
e.insert...
but it hasn't helped. I've seen other examples of people trying to use an object in a list, and it seems they are just doing as I did in my first attempt. Have I missed something?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Entry(root).grid()
返回一个NoneType
对象,因此您在列表中存储的所有内容都是None
。您可以先创建Entry
小部件,调用grid()
,然后将其附加到列表中。Entry(root).grid()
returns aNoneType
object, so all you are storing in your list isNone
. You can create theEntry
widget first, callgrid()
and then append it to your list.我之前刚开始Python的时候也遇到过这个问题。我当时想,“为什么要用两行来创建一些东西并设置网格位置。我会把它们全部放在一行上。”有趣的故事,“.grid”返回 None。所以我认为你实际上并没有在这里添加任何内容。
I ran into this problem before when I started Python. I was like, "Why take up two lines creating something and setting the grid location. I'll put it all on one." Funny story, the '.grid' returns None. So I don't think you're actually appending anything here.