我正在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.

09-26 21:08
查看更多