首页 > 解决方案 > 当我按下它时,停止按钮改变它的浮雕。(Tkinter)

问题描述

好样的!我正在尝试用 Tkinter 做一个简单的计算器,我想要的是当我按下一个按钮时它不会改变浮雕并保持FLAT. 问题是它不断更改为GROOVE.

这是代码行:

button1 = tk.Button(self, text="1", command=lambda: self.config(relief=FLAT), relief=FLAT,
                            font=myfont, bg="ghost white", activebackground="LightSteelBlue2")

我将不胜感激。

编辑

我想要按钮做的是这样的,就像 Windows Calculator 的按钮在此处输入图像描述

标签: pythontkinter

解决方案


如果您希望标签即使在被按下时也保持平坦,您可以使用标签。以为我不确定为什么您不希望某些视觉 q 显示它已被单击。

这是一个使用 A 按钮和标签的示例。请注意,标签在我们使用时就像一个按钮,bind()但在视觉上没有变化。

import tkinter as tk


def do_something(value):
    print(value)


root = tk.Tk()
# Normal button behavior.
tk.Button(root, text="Button 1", relief='flat', bg="ghost white",
          activebackground="LightSteelBlue2",
          command=lambda: do_something("Button 1")).pack()

# Is a button but does not change visuals when clicked due to state='disabled' and bind combination.
# Downside the text is greyed out.
button_2 = tk.Button(root, text="Button 2", relief='flat', bg="ghost white",
                     activebackground="LightSteelBlue2", state='disabled')
button_2.pack()
button_2.bind("<Button-1>", lambda e: do_something("Button 2"))

# Is a label but works like a button due to bind.
# This method should fit your needs.
label_1 = tk.Label(root, text="Label 1", bg="ghost white", activebackground="LightSteelBlue2")
label_1.pack()
label_1.bind("<Button-1>", lambda e: do_something("Label 1"))

root.mainloop()

更新:

根据您在下面的评论“我希望按钮在按下时更改其颜色,在未按下时返回其正常状态。” 这就是我如何获得您正在寻找的功能。

import tkinter as tk


def change_color(event):
    event.widget.config(bg='green')
    entry.insert('end', event.widget['text'])


def change_back(event):
    event.widget.config(bg='ghost white')


root = tk.Tk()
num_pad = [[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]]

entry = tk.Entry(root, width=50)
entry.grid(row=0, column=0)

pad_frame = tk.Frame(root)
pad_frame.grid(row=1, column=0)
# Is a label but works like a button due to bind.
# This method should fit your needs.
for ndex, sub_list in enumerate(num_pad):
    for sub_ndex, sub_value in enumerate(sub_list):
        lbl = tk.Label(pad_frame, text=sub_value, bg="ghost white", activebackground="LightSteelBlue2",
                       height=2, width=3)
        lbl.grid(row=ndex, column=sub_ndex, padx=2, pady=2)
        lbl.bind("<Button-1>", change_color)
        lbl.bind("<ButtonRelease-1>", change_back)
        lbl.bind("<Leave>", change_back)
root.mainloop()

推荐阅读