如何使用单选按钮解决问题?

时间:2020-04-17 18:14:27

标签: python tkinter

好的,我无法按提示进行操作。相反,即使在被选择之前,它们都只是为猜测变量打印相同的值,如果我将其设置为“无”,则会被打印四次....而且我不知道该怎么办。这是代码:

from tkinter import*
root = Tk()
root.title("KVIZOMANIJA")
root.geometry("800x600")
app = Frame(root)
app.grid()
guess = StringVar()
guess.set("opa")
odg1 = Radiobutton(app,text = "prvi gumbek", variable = guess, value = "a", command =print(guess.get()))
odg1.grid(row=4, column = 0, columnspan= 2, sticky = W)
odg2 = Radiobutton(app,text="drugi gumbek", variable = guess, value = "b", command = print(guess.get()))
odg2.grid(row=5, column = 0, columnspan= 2, sticky = W)
odg3 = Radiobutton(app,text="treci gumbek", variable = guess, value = "c", command = print(guess.get()))
odg3.grid(row=6, column = 0, columnspan= 2, sticky = W)
odg4 = Radiobutton(app,text="cetvrti gumbek", variable = guess, value = "d", command = print(guess.get()))
odg4.grid(row=7, column = 0, columnspan= 2, sticky = W)
root.mainloop()

就这样...。

1 个答案:

答案 0 :(得分:2)

我可能看到了您的问题:这是因为您没有在“ command”参数中设置函数,而是设置了指令。您应该替换

command =print(guess.get())

通过

command=lambda x: print(guess.get())

lambda是一种只包含一条指令的匿名函数,它可以返回指令的结果。

您还可以这样定义一个普通函数:

def get_guess():
    print(guess.get())

from tkinter import*
root = Tk()
root.title("KVIZOMANIJA")
root.geometry("800x600")
app = Frame(root)
app.grid()
guess = StringVar()
guess.set("opa")
odg1 = Radiobutton(app,text = "prvi gumbek", variable = guess, value = "a", command=get_guess)
odg1.grid(row=4, column = 0, columnspan= 2, sticky = W)
odg2 = Radiobutton(app,text="drugi gumbek", variable = guess, value = "b", command=get_guess)
odg2.grid(row=5, column = 0, columnspan= 2, sticky = W)
odg3 = Radiobutton(app,text="treci gumbek", variable = guess, value = "c", command=get_guess)
odg3.grid(row=6, column = 0, columnspan= 2, sticky = W)
odg4 = Radiobutton(app,text="cetvrti gumbek", variable = guess, value = "d", command=get_guess)
odg4.grid(row=7, column = 0, columnspan= 2, sticky = W)
root.mainloop()