为什么tkinter python组合框代码返回错误的输出?

2024-04-19 00:27:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望第二个组合框cbo_forecast_ps在选择第一个组合框cbo_forecast_w中的项目时显示某些值。你知道吗

from Tkinter import *
import tkMessageBox
import ttk
from ttk import *

masterframe =Tk()
# Create right frame for general information
rightFrame = Frame(masterframe,width 
=600,height=300,borderwidth=2,relief=SOLID,)
rightFrame.place(x=610,y=0)

for_w_text =StringVar()
cbo_forecast_w = ttk.Combobox (rightFrame, textvariable=for_w_text)
cbo_forecast_w['values']=("cow","chicken","ant")

string_text =StringVar()
cbo_forecast_ps = ttk.Combobox (rightFrame,textvariable=string_text)

def choosestring():
    forecast_w= for_well_text.get()
    lbl_test.configure(text = forecast_w)
    if forecast_w=="cow":
        cbo_forecast_ps['values'] = ("single")
        cbo_forecast_ps.current(0)
    else:
        cbo_forecast_ps['values'] = ("Short", "Long")
        cbo_forecast_ps.current(0)        

# I hope this is correct

cbo_forecast_w.bind("<<ComboboxSelected>>",choosestring())

我发现forecast_w不是从for_well_text.get()取值。相反,它在释放PY_VAR2。你知道吗

如何解决这个问题?你知道吗


Tags: textfromimportforpsvaluesttkforecast
1条回答
网友
1楼 · 发布于 2024-04-19 00:27:48

这是您发布的代码的简化版本,在您的代码中有一些错误您没有创建label来配置它,并且在您的注释中您声明您正在获得PY_VAR2,您应该使用get来接收combobox中的内容。你知道吗

要在小部件中接收内容,可以使用for_w_text.get()而不使用stringvar,而只需像插入cbo_forecast_pstin widget之前那样进行比较。你知道吗

from Tkinter import *
import tkMessageBox
import ttk
from ttk import *


def choosestring(event=None):
    nf = cbo_forecast_w.get() # get the conten in the combo box

    lbl_test.configure(text = nf)  # label to configure
    if for_w_text.get()=="cow":
        cbo_forecast_ps['values'] = ("single")
        cbo_forecast_ps.current(0)
    else:
        cbo_forecast_ps['values'] = ("Short", "Long")
        cbo_forecast_ps.current(0)

# I hope this is correct


masterframe =Tk()
# Create right frame for general information
rightFrame = Frame(masterframe,width
=600,height=300,borderwidth=2,relief=SOLID,)
rightFrame.place(x=610,y=0)

for_w_text =StringVar()
cbo_forecast_w = ttk.Combobox (rightFrame, textvariable=for_w_text)
cbo_forecast_w['values']=("cow","chicken","ant")
cbo_forecast_w.pack()


string_text =StringVar()
cbo_forecast_ps = ttk.Combobox (rightFrame,textvariable=string_text)
cbo_forecast_ps.pack()


lbl_test = Label(rightFrame)
lbl_test.pack()


cbo_forecast_w.bind("<<ComboboxSelected>>",choosestring)

masterframe.mainloop()

相关问题 更多 >