如何在Tkinter中获取按钮控件文本?调用cget方法失效问题求解
错误原因
- 你在创建组件时直接链式调用了
place()方法,Tkinter的pack/grid/place三大布局方法返回值都是None,所以你赋值给dataset_1/random_forest这些变量的其实是None,调用cget方法自然会报错。 - 你用普通Button来做数据集选择,没有做选中状态标记,没法判断用户选了哪个数据集,改成单选框组件更符合选择场景。
- 算法选择的单选框
value属性现在设的是Male/Female,和实际选项文本不对应,拿到值也没法判断选的是哪个算法。 printit函数要定义在组件创建之前,不然组件绑定command的时候找不到这个函数会报错。- 窗口高度只有600,你把提示Label放在y=780的位置超出窗口范围,无法正常显示。
修正后可运行代码
from tkinter import * def printit(): # 读取选中的数据集 selected_dataset = dataset_var.get() # 读取选中的算法 selected_algo = algo_var.get() # 仅当两个选项都选中才执行逻辑 if selected_dataset and selected_algo: if selected_dataset == "dataset 1" and selected_algo == "Random Forest": Label(win,text="yes",fg="blue",bg="yellow",font = ("Calibri 10 bold")).place(x=12,y=500) else: Label(win,text=f"已选择:{selected_dataset} + {selected_algo}",fg="blue",bg="yellow",font = ("Calibri 10 bold")).place(x=12,y=500) win = Tk() win.geometry("400x600") win.configure(background="cyan") win.title("Registration Form") title = Label(win, text="Ensemble Methods", bg="gray", width="300", height="2", fg="white", font = ("Calibri 20 bold italic underline")).pack() # 数据集改为单选框实现选择逻辑 dataset_var = StringVar() dataset_1 = Radiobutton(win, text="dataset 1", width="12",height="1",activebackground="violet", bg="Pink",variable=dataset_var,value="dataset 1",font = ("Calibri 12 ")) dataset_1.place(x=20, y=200) dataset_2 = Radiobutton(win, text="dataset 2", width="12",height="1",activebackground="violet", bg="Pink",variable=dataset_var,value="dataset 2",font = ("Calibri 12 ")) dataset_2.place(x=150, y=200) dataset_3 = Radiobutton(win, text="dataset 3", width="12",height="1",activebackground="violet", bg="Pink",variable=dataset_var,value="dataset 3",font = ("Calibri 12 ")) dataset_3.place(x=280, y=200) # 修正算法单选框的value属性,和选项文本对应 algo_var = StringVar() random_forest = Radiobutton(win, text="Random Forest",bg="cyan",variable=algo_var,value="Random Forest",font = ("Verdana 12")) random_forest.place(x=20,y=340) AdaBoost = Radiobutton(win, text="Ada Boost",bg="cyan",variable=algo_var,value="Ada Boost",font = ("Verdana 12")) AdaBoost.place(x=280,y=340) submit = Button(win, text="Submit", width="12",height="1",activebackground="violet", bg="Pink",command=printit,font = ("Calibri 12 ")) submit.place(x=240, y=540) win.mainloop()
内容的提问来源于stack exchange,提问作者mouhamad
相关产品推荐
相关产品推荐

