gpt4 book ai didi

python - 根据Python中组合框选择的值在文本框中显示特定值

转载 作者:太空宇宙 更新时间:2023-11-03 16:22:24 25 4
gpt4 key购买 nike

如何在文本框小部件中显示组合框值?

这是我的编码,它说我需要放置事件参数,那么我应该放置什么事件参数才能在文本框小部件中显示我的组合框值?

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()

最佳答案

问题不在于将哪个事件参数传递给 textArea () 方法:您必须修复以下错误:

  1. 首先,删除对 textArea() 的调用里面__init__() ,而是combo()需要它。
  2. 内部textArea()每次回调 combo() 时,您都会创建一个新的文本小部件叫做。因此,您需要从 textArea() 移动创建和定位文本小部件的这两行。至combo()相反。
  3. 一旦解决了这个问题,算法就很简单:当从组合框小部件中选择一个值时,您需要检查文本小部件是否为空:如果是,则直接插入该值,如果不是,则在插入之前删除现有文本。

程序:

以下是已修复相关错误的解决方案:

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()

关于python - 根据Python中组合框选择的值在文本框中显示特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38312494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com