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

PyCharm基于Tkinter开发GUI多按钮开关无法同时生效及默认黑背景设置问题

问题修复方案

问题1:多开关无法同时正常运行修复

  • 移除多余的Tk()实例master及其相关代码,master.mainloop()为阻塞方法,会导致后续root窗口逻辑无法正常执行。
  • 修正switch2函数逻辑:第二个开关仅需操作同一个按钮切换图片即可,原代码else分支错误修改未挂载的reverse_button配置,导致点击无响应。
  • 移除所有重复的mainloop()调用和mainloop()之后的无效代码,mainloop()是窗口事件循环阻塞方法,其后的代码仅会在窗口关闭后执行,不会生效。
  • 移除代码中不存在的变量(forward、reverse、update)相关的无效调用。

问题2:黑色背景默认生效修复

原代码仅在开关点击回调中配置按钮黑色背景,初始创建按钮时未指定背景参数,默认使用系统灰色背景。在创建按钮时直接添加bg='black'参数即可默认生效。


修正后可运行代码

import tkinter
from tkinter import *
import tkinter.font as tkFont
from PIL import ImageTk, Image
import serial
import time
import os

root = Tk()
root.config(bg='black')

rootWidth = root.winfo_screenwidth()
rootHeight = root.winfo_screenheight()

is_on = True
is_forward = True

# 此部分代码可实现所有显示器下字体大小恒定
normalWidth = 1920
# 编写代码所用显示器的宽度
normalHeight = 1080
# 编写代码所用显示器的高度

percentWidth = rootWidth / (normalWidth / 100)
percentHeight = rootHeight / (normalHeight / 100)
scale = ((percentWidth + percentHeight) / 2) / 100
fontstyle = tkFont.Font(family='Cambria', size=50)

def switch():
    global is_on
    if is_on:
        on_button.config(image=on)
        is_on = False
    else:
        on_button.config(image=off)
        is_on = True

def switch2():
    global is_forward
    if is_forward:
        forward_button.config(image=reverse2)
        is_forward = False
    else:
        forward_button.config(image=forward2)
        is_forward = True

forward2 = Image.open("C:/Users/LattePanda/Desktop/images/LedOn.png")
reverse2 = Image.open("C:/Users/LattePanda/Desktop/images/LedOff.png")

on = Image.open("C:/Users/LattePanda/Desktop/images/forward.png")
off = Image.open("C:/Users/LattePanda/Desktop/images/reverse.png")

resizeOn = on.resize((600,600),Image.ANTIALIAS)
resizeOff = off.resize((600,600),Image.ANTIALIAS)

resizeOn2 = forward2.resize((400,400),Image.ANTIALIAS)
resizeOff2 = reverse2.resize((400,400),Image.ANTIALIAS)

on = ImageTk.PhotoImage(resizeOn)
off = ImageTk.PhotoImage(resizeOff)

forward2 = ImageTk.PhotoImage(resizeOn2)
reverse2 = ImageTk.PhotoImage(resizeOff2)

# 创建按钮时直接指定所有固定配置,无需重复设置
on_button = Button(root, image=on, bd=0, bg='black', activebackground='black', command=switch)
on_button.pack(pady=50)

forward_button = Button(root, image=forward2, bd=0, bg='black', activebackground='black', command=switch2)
forward_button.pack(pady=50)

root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:27:03