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

Ubuntu系统中Tkinter按钮失效问题求助

按钮在Ubuntu失效的原因及修复方案
  • 代码绑定错误:按钮的command参数写法有误,lambda: self.app_exit只是指向了方法对象,没有触发方法执行。正确写法二选一:

    • 直接绑定方法:command=self.app_exit
    • 用lambda调用方法:command=lambda: self.app_exit()
  • Linux窗口管理器兼容性问题:开启overrideredirect(True)后,Ubuntu的窗口管理器可能会让窗口无法获取鼠标焦点,导致按钮接收不到点击事件。可以在__init__方法末尾添加self.focus_force(),强制窗口获取焦点。

修复后的完整代码:

import tkinter as tk
from tkinter import ttk
import sys

class Application(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.attributes("-alpha", 1)
        self.attributes("-topmost", True)
        self.overrideredirect(True)
        self.resizable(False, False)
        self.title("CPU-RAM usage monitor bar")

        self.set_ui()
        self.focus_force()  # 强制窗口获取焦点

    def set_ui(self):
        # 修复command绑定
        exit_but = tk.Button(self, text="Exit", command=self.app_exit)
        exit_but.pack(fill=tk.X)


    def app_exit(self):
        self.destroy()
        sys.exit()


root = Application()
root.mainloop()

内容的提问来源于stack exchange,提问作者Дмитрий Савицкий

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:15:39