如何在文本框小部件中显示组合框值?
这是我的编码,它说我需要放置事件参数,那么我应该放置什么事件参数才能在我的文本框小部件中显示我的组合框值?
from tkinter import *
from tkinter import ttk
class Application:
def __init__(self, parent):
self.parent = parent
self.value_of_combo='A'
self.combo()
self.textArea()
def textArea(self,event):
self.value_of_combo = self.box.get()
print(self.value_of_combo)
thistextArea=Text(self.parent,height=50,wideth=50)
thistextArea.grid(column=0,row=1)
def combo(self):
self.box_value = StringVar()
self.box = ttk.Combobox(self.parent, textvariable=self.box_value,values=('A', 'B', 'C'),state='readonly')
self.box.bind('<<ComboboxSelected>>',self.textArea)
self.box.current(0)
self.box.grid(column=0, row=0)
root = Tk()
app = Application(root)
root.mainloop()
答案 0 :(得分:1)
The problem is not about which event argument to pass to textArea
() method: you rather have to fix the following errors:
textArea()
inside __init__()
, it is rather combo()
that needs it.textArea()
you are creating a new Text widget each time the callback combo()
is called. So you need to move those 2 lines that create and position the Text widget from textArea()
to combo()
instead.Program:
Here is the solution with the related errors fixed:
from tkinter import *
from tkinter import ttk
class Application:
def __init__(self, parent):
self.parent = parent
self.value_of_combo='A'
self.combo()
#self.textArea() <-- This has nothing to do here, remove it
def textArea(self, e):
self.value_of_combo = self.box.get()
print(self.value_of_combo)
# Get the content of the Text widget
r=self.thistextArea.get('1.0','1.end')
# If it is empty then insert the selected value directly
if not r:
self.thistextArea.insert(INSERT, self.value_of_combo)
# If not empty then delete existing text and insert the selected value
else:
self.thistextArea.delete('1.0','1.end')
self.thistextArea.insert(END, self.value_of_combo)
def combo(self):
self.box_value = StringVar()
self.box = ttk.Combobox(self.parent, textvariable=self.box_value,values=('A', 'B', 'C'),state='readonly')
self.box.bind('<<ComboboxSelected>>',self.textArea)
self.box.current(0)
self.box.grid(column=0, row=0)
self.thistextArea=Text(self.parent,height=50,width=50)
self.thistextArea.grid(column=0,row=1)
root = Tk()
app = Application(root)
root.mainloop()