我在Python 3.5中开始GUI,我正在尝试设置一个简单的qwerty键盘。根据示例,我尝试了以下代码
from tkinter import Tk, Label, RAISED, Button, Entry
self.window = Tk()
#Keyboard
labels = [['q','w','e','r','t','y','u','i','o','p'],
['a','s','d','f','g','h','j','k','l'],
['z','x','c','v','b','n','m','<']]
n = 10
for r in range(3):
for c in range(n):
n -= 1
label = Label(self.window,
relief=RAISED,
text=labels[r][c])
label.grid(row=r,column=c)
continue
这给了我第一行,但它没有返回任何其他内容。我尝试简单地使用 10 作为范围,这创建了键盘的前两行,但它仍然没有继续到最后一行。
您的问题出在行n -= 1
中。每次创建标签时,您都会在第一整行之后少n
一个标签,n==0
,因此范围为 0>0,并且范围永远不会包括上限 - for c in range(0)
只会从循环中删除(因为它已经循环了所有不存在的内容)。
更好的解决方案涉及遍历列表而不是索引 - for
循环采用任何可迭代对象(列表、字典、范围、生成器、集合等);
for lyst in labels:
# lyst is each list in labels
for char in lyst:
# char is the character in that list
label = Label(... text=char) # everything else in the Label() looks good.
label.grid(...) # You could use counters for this or use ennumerate()-ask if you need.
# The continue here was entirely irrelevant.
这是你想要它做的吗?如果您需要我进一步解释,请告诉我,但基本上我正在做的是首先填充每行的列。所以行保持为 0,然后当我遍历列(内部列表)时,我填写每个键,然后转到下一行,依此类推。
from tkinter import Tk, Label, RAISED, Button, Entry
window = Tk()
#Keyboard
labels = [['q','w','e','r','t','y','u','i','o','p'],
['a','s','d','f','g','h','j','k','l'],
['z','x','c','v','b','n','m','<']]
for r in labels:
for c in r:
label = Label(window, relief=RAISED, text=str(c))
label.grid(row=labels.index(r), column=r.index(c))
window.mainloop()