我正试图找到一种方法Tkinter,使Start
按钮一直被按下,直到我按下Stop
按钮。
from Tkinter import *
import tkMessageBox
class MainWindow(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("input")
self.master.minsize(250, 150)
self.grid(sticky=E+W+N+S)
top=self.winfo_toplevel()
top.rowconfigure(0, weight=1)
top.columnconfigure(0, weight=1)
for i in range(2):self.rowconfigure(i, weight=1)
self.columnconfigure(1, weight=1)
self.button0 = Button(self, text="Start", command=self.save, activeforeground="red")
self.button0.grid(row=0, column=0, columnspan=2, pady=2, padx=2, sticky=E+W+N+S)
self.button1 = Button(self, text="Stop", command=self.stop, activeforeground="red")
self.button1.grid(row=1, column=0, columnspan=2, pady=2, padx=2, sticky=E+W+N+S)
def save(self):
pass
def stop(self):
pass
if __name__=="__main__":
d=MainWindow()
d.mainloop()
因此,您可以使用其配置来设置按钮的释放,这使其看起来像是被按下了一样。
def save(self):
self.button0.config(relief=SUNKEN)
# if you also want to disable it do:
# self.button0.config(state=tk.DISABLED)
#...
def stop(self):
self.button0.config(relief=RAISED)
# if it was disabled above, then here do:
# self.button0.config(state=tk.ACTIVE)
#...
编辑
这显然在Mac OSx上不起作用。此链接显示中的外观:http://www.tutorialspoint.com/python/tk_relief.htm
如果Tkinter.Button
不允许在系统上配置其relief
属性,那么您可以尝试基于ttk.Button
的代码:
try:
import Tkinter as tk
import ttk
except ImportError: # Python 3
import tkinter as tk
import tkinter.ttk as ttk
SUNKABLE_BUTTON = 'SunkableButton.TButton'
root = tk.Tk()
root.geometry("400x300")
style = ttk.Style()
def start():
button.state(['pressed', 'disabled'])
style.configure(SUNKABLE_BUTTON, relief=tk.SUNKEN, foreground='green')
def stop():
button.state(['!pressed', '!disabled'])
style.configure(SUNKABLE_BUTTON, relief=tk.RAISED, foreground='red')
button = ttk.Button(root, text ="Start", command=start, style=SUNKABLE_BUTTON)
button.pack(fill=tk.BOTH, expand=True)
ttk.Button(root, text="Stop", command=stop).pack(fill=tk.BOTH, expand=True)
root.mainloop()
我知道为时已晚,您可能已经找到了解决方案,但这个答案可能对其他人有所帮助。
解决方案是使用Radio Button
。创建Radio Button
的主要动机与您的问题相同。
下面是GeeksforGeeks网站上的一个例子:
# Importing Tkinter module
from tkinter import *
# from tkinter.ttk import *
# Creating master Tkinter window
master = Tk()
master.geometry("175x175")
# Tkinter string variable
# able to store any string value
v = StringVar(master, "1")
# Dictionary to create multiple buttons
values = {"RadioButton 1" : "1",
"RadioButton 2" : "2",
"RadioButton 3" : "3",
"RadioButton 4" : "4",
"RadioButton 5" : "5"}
# Loop is used to create multiple Radiobuttons
# rather than creating each button separately
for (text, value) in values.items():
Radiobutton(master, text = text, variable = v,
value = value, indicator = 0,
background = "light blue").pack(fill = X, ipady = 5)
# Infinite loop can be terminated by
# keyboard or mouse interrupt
# or by any predefined function (destroy())
mainloop()
此外,您可以创建按钮函数并实现您想要的输出。