【问题标题】:Tkinter: Change button background when pressedTkinter:按下时更改按钮背景
【发布时间】:2021-01-12 19:58:19
【问题描述】:

我知道我应该使用bttn['text'] = 'text',但我正在使用 for 创建按钮。我想在按下按钮时将其颜色更改为红色。

示例代码:

from tkinter import *

root = Tk()

btn = [i for i in range(10)]

for i in range(len(btn)):
    b = Button(root, text=str(i), command=lambda c=i: print(i))
    b.pack()

root.mainloop()

我需要替换什么print(i)

【问题讨论】:

  • 您希望按钮在单击后永久变为红色,还是仅在单击后返回正常颜色?

标签: python tkinter


【解决方案1】:

为此,您需要将 Button 对象“b”传递给回调函数。为此,您需要在下一行设置命令,以便“b”对象可用。像这样:

from tkinter import *

root = Tk()

def change_to_red(bttn):
    bttn.config(bg='red', activebackground='red') # same as bttn['bg'] = 'red';  bttn['activebackground'] = 'red'
    print(bttn['text'])

btn = [i for i in range(10)]

for i in range(len(btn)):
    b = Button(root, text=str(i), width=6)
    b.config(command=lambda c=b: change_to_red(c))
    b.pack()

root.mainloop()

但实际上这将是学习子类的好地方。您可以修改 tkinter 的 Button 以制作您自己的 Button 类型,除了正常操作之外,它还可以执行您想要的操作:

import tkinter as tk

class Desync192Button(tk.Button):
    def __init__(self, master=None, **kwargs):
        self.command = kwargs.pop('command', None)
        super().__init__(master, command=self.on_click, **kwargs)
    def on_click(self):
        self.config(bg='red', activebackground='red')
        if self.command: self.command()

# demo:
root = tk.Tk()

for i in range(10):
    b = Desync192Button(root, text=i, width=6, command=lambda c=i: print(c))
    b.pack()

root.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多