我刚开始使用python。我有一些ComboBox,我想在标签上打印所选值。对我来说很难,因为我使用字典。
有人可以帮助我在标签上打印combobox值吗?
from tkinter import *
from tkinter import ttk
class NewCBox(ttk.Combobox):
def __init__(self, master, dictionary, *args, **kw):
ttk.Combobox.__init__(self, master, values=sorted(list(dictionary.keys())),
state='readonly', *args, **kw)
self.dictionary = dictionary
# purely for testing purposes
self.bind('<<ComboboxSelected>>', self.selected)
def value(self):
return self.dictionary[self.get()]
def selected(self, event): # Just to test
print((self.value()))
class NewCBox1(ttk.Combobox):
def __init__(self, master, dictionary, *args, **kw):
ttk.Combobox.__init__(self, master, values=sorted(list(dictionary.keys())),
state='readonly', *args, **kw)
self.dictionary = dictionary
# purely for testing purposes
self.bind('<<ComboboxSelected>>', self.selected)
def value(self):
return self.dictionary[self.get()]
def selected(self, event): # Just to test
print((self.value()))
lookup = {'Arkitekt': 'A', 'Geoteknik': 'B',
'Ingeniør Anlæg': 'C', 'Procesanlæg': 'D'}
documentcode = {'Aftaler': 'AGR', 'Analyse': 'ANA',
'Myndigheder': 'AUT', 'Sagsbasis': 'BAS'}
root = Tk()
newcb = NewCBox(root, lookup)
newcb.pack()
newcb1 = NewCBox1(root, documentcode)
newcb1.pack()
root.mainloop()
您实际上不需要两个类,而只需要一个。如果您观察到良好的代码,您会注意到这两个课程几乎相同,但是具有不同的字典。因此,您可以通过传递到__init__
值2个不同字典来实例化2个对象。
如果您想要一个Label
,每当您从组合中选择某些内容时,我不会从ttk.Combobox
继承而来,而是从Frame
继承,以便可以使用ttk.Combobox
和Label
。
要设置Label
的文本,您可以使用所有小部件共有的方法config(...)
。
请参阅下面的示例(如果您有其他问题作为评论):
import tkinter as tk
from tkinter import ttk
class LabeledCombobox(tk.Frame):
def __init__(self, master, dictionary, *args, **kw):
tk.Frame.__init__(self, master, *args, **kw)
self.dictionary = dictionary
self.combo = ttk.Combobox(self, values=sorted(list(dictionary.keys())),
state='readonly')
self.combo.current(0)
self.combo.pack(fill="both")
self.combo.bind('<<ComboboxSelected>>', self.on_selection)
self.label = tk.Label(self, text=self.value())
self.label.pack(fill="both", expand=True)
def value(self):
return self.dictionary[self.combo.get()]
def on_selection(self, event=None): # Just to test
self.label.config(text=self.value())
lookup = {'Arkitekt': 'A', 'Geoteknik': 'B',
'Ingeniør Anlæg': 'C', 'Procesanlæg': 'D'}
documentcode = {'Aftaler': 'AGR', 'Analyse': 'ANA',
'Myndigheder': 'AUT', 'Sagsbasis': 'BAS'}
if __name__ == "__main__":
root = tk.Tk()
root.title("Labeled comboboxes")
combo1 = LabeledCombobox(root, lookup, bd=1, relief="groove")
combo1.pack(side="left", padx=(2, 2), pady=5)
combo2 = LabeledCombobox(root, documentcode, bd=1, relief="groove")
combo2.pack(side="right", padx=(2, 2), pady=5)
root.mainloop()