Skip to main content
 首页 » 编程设计

python之初学者 Python 键盘 GUI 设置

2025年04月02日39lautakyan007

我开始使用 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.