我正在尝试创建一个GUI,用户可以从列表框中选择一个值并存储它。用户将有多个要选择的内容,但每个列表框只能选择一个。目前我有一个带有nessecary属性的列表框。它是使用以下代码生成的:
from tkinter import *
class MyApp:
def __init__(self, parent):
self.myParent = parent #the root
#select setup
list = {"Setup 1","Blue Setup","Setup 12","Broken Setup","Noise Generator"}
msg = "Select Setup"
self.SVAL = 0;
self.Sframe = Frame(parent)
self.Sframe.pack()
self.Slabel = Label(self.Sframe,text=msg)
self.Slabel.pack()
self.Sbox = Listbox(self.Sframe)
for item in list:
self.Sbox.insert(END,item)
self.Sbox.pack()
self.Sbut = Button(self.Sframe,text="select", command=self.Sselect)
self.Sbut.pack()
self.Smess = Message(self.Sframe,text="Go")
self.Smess.pack()
def Sselect(self):
print(self.Sbox.curselection())
self.SVAL = self.Sbox.curselection()
self.Smess.configure(text=self.Sbox.get(self.SVAL[0]))
root = Tk()
myapp = MyApp(root)
root.mainloop()
我想在它的右边生成第二帧,但如果我不必重复代码就会很好。目标是重复这个GUI块,只更改列表和msg变量,所以我会有像
这样的东西list = {"Setup 1","Blue Setup","Setup 12","Broken Setup","Noise Generator"}
msg = "Select Setup"
self.S = generateblock(list,msg)
list = {"Joe","George","Harry"}
msg = "Select User"
self.U = generateblock(list,msg)
我希望这是可能的。
答案 0 :(得分:1)
您的"列表"不是列表,会产生错误。您还必须跟踪选择号码来自哪个列表框。一个简单的修改来展示这个概念。
from tkinter import *
from functools import partial
class MyApp:
def __init__(self, parent):
self.myParent = parent #the root
self.listbox_instances=[]
#select setup
list_of_choices = [["Setup 1","Blue Setup","Setup 12","Broken Setup",
"Noise Generator"],
["test 2a", "test 2b", "test 2c"],
["test 3a", "test 3b", "test 3c"],]
msg = "Select Setup"
##self.SVAL = 0;
for ctr in range(3):
self.Sframe = Frame(parent)
self.Sframe.grid(row=0, column=ctr)
self.Slabel = Label(self.Sframe,text=msg)
self.Slabel.pack()
self.Sbox = Listbox(self.Sframe)
for item in list_of_choices[ctr]:
self.Sbox.insert(END,item)
self.Sbox.pack()
self.listbox_instances.append(self.Sbox)
## send the listbox number with the command call
self.Sbut = Button(self.Sframe,text="select",
command=partial(self.Sselect, ctr))
self.Sbut.pack()
self.Smess = Message(self.Sframe,text="Go")
self.Smess.pack()
def Sselect(self, this_num):
print("box_num=%d & item num=%s" % (this_num,
self.listbox_instances[this_num].curselection()))
## self.SVAL = self.Sbox.curselection()
## self.Smess.configure(text=self.Sbox.get(self.SVAL[0]))
root = Tk()
myapp = MyApp(root)
root.mainloop()