如何一次选择一个tkinter按钮

时间:2017-11-22 11:15:33

标签: python button tkinter

我希望我的tkinter按钮在选中之前被提升,然后可以打印条目中的内容,但是可以选择同时引发两个按钮。我希望我的小部件采取行动的所有行为仅表现为能够同时选择两个按钮,我希望一次按下一个按钮。

import tkinter as tk


def output():

    global choosed

    if choosed:
        now = new.get()
        print(now)
    else:
        print("select predict button to proceed")


def raised_button(button_object):

    global choosed
    choosed = True

    button_object.configure(relief=tk.SUNKEN, state=tk.DISABLED)


def stop():

    global choosed
    choosed = False

    lot1.configure(relief=tk.RAISED, state=tk.ACTIVE)
    lot2.configure(relief=tk.RAISED, state=tk.ACTIVE)



root = tk.Tk()
root.geometry("400x400")


new = tk.StringVar()
en = tk.Entry(root, textvariable=new).pack()

choosed = False


lot1 = tk.Button(root, text="GOOD")
lot1.configure(command=lambda button_object=lot1: 
raised_button(button_object))
lot1.pack(side="left")


lot2 = tk.Button(root, text="BAD")
lot2.configure(command=lambda button_object=lot2: 
raised_button(button_object))
lot2.pack()


tk.Button(root, text="print number", command=lambda :[output(),
stop()]).place(x=150, y=300)

root.mainloop()

如果选择了按钮GOOD,则仅对其应用凹陷,如果对其应用了选择按钮BAD凹陷效果,则会禁用按钮Good凹陷效果。

1 个答案:

答案 0 :(得分:2)

据我所知,只有一个按钮可以沉没。如果单击第二个按钮,则第一个按钮(凹陷)必须再次抬起。

您可以在stop()内使用raise_button()

def raised_button(button_object):
    global choosed
    choosed = True

    stop()

    button_object.configure(relief=tk.SUNKEN, state=tk.DISABLED)

或者您可以使用choosed来记住按钮并在点击其他按钮时将其抬起。

def raised_button(button_object):
    global choosed

    if choosed: # previously clicked
        choosed.configure(relief=tk.RAISED, state=tk.ACTIVE)

    choosed = button_object
    button_object.configure(relief=tk.SUNKEN, state=tk.DISABLED)

def stop():
    global choosed

    choosed = None

    lot1.configure(relief=tk.RAISED, state=tk.ACTIVE)
    lot2.configure(relief=tk.RAISED, state=tk.ACTIVE)

#----

choosed = None # set at start

编辑:您也可以将Radiobuttonsindicatoron=0一起使用,它们看起来像普通按钮,但仍然只能选择一个Radiobutton

import tkinter as tk

root = tk.Tk()

v = tk.IntVar()

tk.Radiobutton(root, text="One", variable=v, value=1, indicatoron=0).pack()
tk.Radiobutton(root, text="Two", variable=v, value=2, indicatoron=0).pack()

tk.Button(root, text='Reset', command=lambda:v.set(0)).pack()

root.mainloop() 

有关effbot.org的更多信息,请访问:Radiobutton