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

tkinter:LabelFrame在独立TopLevel窗口中显示异常求助

问题解决:单选按钮出现在主窗口而非对话框的原因及修复

核心问题出在你创建LabelFrame的代码行:

frame1 = ttk.Labelframe(self,text='testo').grid(column=0,row=0,padx=20,pady=20)

tkinter中,grid()、pack()、place()这些布局方法的返回值都是None,所以这里frame1实际上被赋值成了None。当你把Radiobutton的父组件设为None时,tkinter会默认使用主窗口作为父容器,这就是单选按钮出现在主窗口的原因。

修复方法很简单:将组件创建和布局操作分开执行,先创建LabelFrame实例并赋值给变量,再单独调用布局方法。同时按钮的创建也建议用同样的方式,避免后续需要操作按钮时遇到问题。

修正后的完整代码:

import tkinter as tk
from tkinter import ttk


class PersonEmptyDocsDialog(tk.Toplevel):
    def __init__(self, root, personid):
        super().__init__(root)
        self.personid = personid
        self.code = tk.StringVar()

        # 先创建LabelFrame,再单独调用grid布局
        frame1 = ttk.Labelframe(self, text='testo')
        frame1.grid(column=0, row=0, padx=20, pady=20)
        
        # 现在Radiobutton的父组件是正确的LabelFrame实例
        ttk.Radiobutton(frame1, text="Option 1", variable=self.code, value="0-0-0").pack()
        ttk.Radiobutton(frame1, text="Option 2", variable=self.code, value="0-0-1").pack()
        ttk.Radiobutton(frame1, text="Option 3", variable=self.code, value="0-0-2").pack()

        # 按钮也分开创建和布局
        self.ok_button = tk.Button(self, text="OK", command=self.on_ok)
        self.ok_button.grid(column=0, row=1)

    def on_ok(self, event=None):
        self.destroy()

    def show(self):
        self.wm_deiconify()
        self.wait_window()
        return self.code.get()

class Example():
    def __init__(self, root):
        # 主框架同样分开创建和布局
        mainframe = ttk.Frame(root)
        mainframe.pack(fill="both", expand=True)
        self.root = root
        ttk.Button(mainframe, text="Get Input", command=self.on_button).pack(padx=8, pady=8)
        ttk.Label(mainframe, text="", width=20).pack(side="bottom", fill="both", expand=True)

    def on_button(self):
        string = PersonEmptyDocsDialog(self.root, 12).show()
        print(string)



root = tk.Tk()
root.wm_geometry("400x200")
Example(root)
root.mainloop()

另外,我把单选按钮的文本改成了不同的内容,方便你区分选择结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:40:16