python - 当我按下它时,停止按钮改变它的浮雕。(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")
我将不胜感激。
编辑
解决方案
如果您希望标签即使在被按下时也保持平坦,您可以使用标签。以为我不确定为什么您不希望某些视觉 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()
推荐阅读
- algorithm - 无法为 while & if 语句找到正确的 Big O
- javascript - 如何避免登录用户通过控制台使用 ajax?
- c# - 将 Asp.net Core API 的结果传递给 Angular
- xml - Adobe LiveCycle:使用 XSLT 进行 XML 到 XML 的转换
- c - 如何查找指针错误?
- python - 设计一个python类
- reactjs - 使用 PHP Laravel 部署 ReactJS 打字稿会出现白屏且没有错误?
- ruby - Ruby Map 函数返回 nil
- c# - 下载文件时如何修复 GDI+ 错误?
- node.js - process.env.NODE_ENV 已设置但仍未定义