You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

选择不同Tkinter Radiobutton时如何消除前一选项效果仅显示对应分区

问题解决方案

问题原因

你代码中每次点击Radiobutton都会新建对应的分区组件,旧的分区没有被隐藏/销毁,所以切换时会同时出现两个分区。

修复思路

  • 初始化阶段提前创建好两个分区,默认设置为隐藏状态,避免每次点击重复创建组件
  • 触发单选切换事件时,先将两个分区全部隐藏,再根据选中的选项显示对应分区

修复后的可运行代码

from tkinter import *

def main():
    root = Tk()
    app = Window(root)
    root.mainloop()


class Window():
    def __init__(self, master):
        self.master=master
        self.master.title("Test")
        self.master.geometry('1000x700')

        self.Radio=Label (self.master, text="Select Method", bg='Lavender')
        self.RadioFrame=LabelFrame(self.master, width=230, height=150, labelwidget=self.Radio, bg='lavender')
        self.RadioFrame.place(x=200, y=35)

        # 将选中状态变量改为实例属性,方便内部调用
        self.selection = IntVar()
        self.selection.set(0)
        r1 = Radiobutton(self.RadioFrame, text="Option 1", variable=self.selection, value=1, command=self.Clicked, bg='lavender').pack()
        r2 = Radiobutton(self.RadioFrame, text="Option 2", variable=self.selection, value=2, command=self.Clicked, bg='lavender').pack()

        # 提前创建两个分区,默认隐藏
        # 分区1
        self.label_1=Label (self.master, text="label 1", bg='lavender')
        self.label_1Frame=LabelFrame(self.master, width=230, height=90, labelwidget= self.label_1, bg='lavender')
        
        # 分区2
        self.label_2=Label (self.master, text="label_2", bg='lavender')
        self.label_2Frame=LabelFrame(self.master, width=230, height=60, labelwidget= self.label_2, bg='lavender')

    def Clicked(self):
        # 先隐藏所有分区
        self.label_1Frame.place_forget()
        self.label_2Frame.place_forget()
        # 再显示对应选中的分区
        if self.selection.get() ==1:
            self.label_1Frame.place(x=490, y=35)
        elif self.selection.get() ==2:
            self.label_2Frame.place(x=490, y=340)

if __name__=='__main__':
    main()

内容的提问来源于stack exchange,提问作者user17356493

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 19:06:07