如何在循环中创建多个具有不同名称的 tkinter 小部件? [英] How can I create multiple tkinter widgets with different names in a loop?

查看:32
本文介绍了如何在循环中创建多个具有不同名称的 tkinter 小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该能够使用循环来执行以下操作,而不是写出比我需要的更多的小部件并缩短我的代码.这就是我现在的做法:

I should be able to use a loop to do the below instead of writing out more widgets than I'll ever need and shorten my code.This is the way I'm doing it now:

db = sqlite3.connect('/path/to/database')
cursor = db.cursor()
cursor.execute("SELECT Drug FROM database where current >= 1")
allrec = cursor.fetchall()
numrec = len(allrec)
cursor.execute("SELECT Drug FROM database where current >= 1")
results = cursor.fetchone()
if numrec == 0:
    exit
else:
    c1=Checkbutton(frame1,variable=var1)
    c1.grid(row=0,column=0,sticky='nw')
    c1.config(bg='black')
    e1=Entry(frame1, bg="black", fg="white")
    e1.grid(row=0, column=1, sticky=NW)
    e1.delete(0, END)
    for row in results:
        e1.insert(END, *results)
results = cursor.fetchone()
if numrec <= 1:
    quit
else:
    c2=Checkbutton(frame1,variable=var2)
    c2.grid(row=1,column=0,sticky='nw')
    c2.config(bg='black')
    e2=Entry(frame1, bg="black", fg="white")
    e2.grid(row=1, column=1, sticky=NW)
    e2.delete(0, END)
    for row in results:
        e2.insert(END, *results)

    record 3 ........
    record 4 ........
    .......
    .......
    record 15 .......

这会创建 15 个具有不同名称的复选框和输入框,以便我可以插入数据库中的记录.

This creates 15 check boxes and entry boxes with different names so I can insert records from my database.

推荐答案

代替有十五个名为 c1c2 的变量... c15,创建一个包含所有复选按钮的列表.对您的条目和变量执行相同的操作.

Instead of having fifteen variables named c1, c2... c15, create a single list which will hold all of your checkbuttons. Do the same for your entries and vars.

checkbuttons = []
entries = []
vars = []
for i in range(numrec):
    results = cursor.fetchone()
    var = IntVar()
    check_button=Checkbutton(frame1,variable=var)
    check_button.grid(row=i,column=0,sticky='nw')
    check_button.config(bg='black')
    entry=Entry(frame1, bg="black", fg="white")
    entry.grid(row=i, column=1, sticky=NW)
    entry.delete(0, END)
    for row in results:
        entry.insert(END, *results)
    checkbuttons.append(check_button)
    entries.append(entry)
    vars.append(var)

现在而不是得到例如e6 的第六个条目,您可以通过 entries[5] 获得它.

Now instead of getting e.g. the sixth entry with e6, you get it with entries[5].

这篇关于如何在循环中创建多个具有不同名称的 tkinter 小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆