我是初学者,正在为树莓派3B +(在python 3中)开发程序。我想编写一个程序来打开和关闭GPIO引脚。我在此尝试使用尽可能少的代码。但是,问题在于,在我创建的for循环中,组合对象没有自己的名称,因此我无法读取它们。我喜欢给他们起名字combo + str(nr),但是python不想这么做。我还想将动作链接到每个选项。有人知道解决方案吗?
这是我的代码:
#imports--------------------------------------------------
from tkinter import *
from tkinter import ttk
#variabelen and defs--------------------------------------------------
在这里,我想放置组合框的定义。再次尽可能短。
#window setup--------------------------------------------------
root = Tk()
root.title("Raspberry Pi - GPIO")
#labels--------------------------------------------------
clm = 0
nr = 1
for a in range (4):
clm = clm+3
for b in range (10):
name = "GPIO"+str(nr)
nr = nr+1
naam = Label(root, text = name)
naam.grid(column = clm, row = b)
#comboboxes--------------------------------------------------
clm = 1
nr = 1
for a in range (4):
clm = clm+3
for b in range (10):
nr = nr+1
optie = ttk.Combobox(root, state="readonly", width = 5, values = ["ON","OFF"])
optie.current(1)
optie.grid(column = clm, row = b)
#white space--------------------------------------------------
clm = 2
for a in range (3):
clm = clm+3
for b in range (10):
naam = Label(root, text = " ")
naam.grid(column = clm, row = b)
#window + mainloop--------------------------------------------------
root.resizable(0,0)
root.mainloop()
对不起,如果我的英语不太好,通常我会说荷兰语。预先谢谢你。
您需要的是对创建的对象的引用,并且不必是名称。您可以使用list
或dict
之类的容器来存储它们。
from tkinter import *
from tkinter import ttk
root = Tk()
root.title("Raspberry Pi - GPIO")
all_combos = {} #create an empty dictionary
for col in range(4):
all_combos[col] = [] #create a list base on column index
for row in range(1,11):
Label(root,text=f"GPIO{col*10+row}").grid(row=row,column=col*2)
c = ttk.Combobox(root, state="readonly", width = 5, values = ["ON","OFF"])
c.current(1)
c.grid(row=row,column=col*2+1)
all_combos[col].append(c) #add each combobox to the column
root.resizable(0,0)
root.mainloop()
现在您将获得一个字典all_combos
,其中存储了所有组合框对象。您可以通过传递索引来访问任何特定的组合框,例如
print (all_combos[0][5].get())
#OFF