简体   繁体   English

Tkinter:如何使按钮为变量分配数字

[英]Tkinter: How do I make a button assign a variable a number

I want to ask the question "Would you like 1,2 or 3 tickets?" 我想问一个问题:“您要购买1,2或3张票吗?” I would like to make it so that there would be 3 buttons, once pressed a variable would be assigned 1,2 or 3. 我想这样做,以便有3个按钮,一旦按下按钮,便会分配1,2或3。

I have tried using message box although that only gives a yes or no answer. 我尝试使用消息框,尽管它只给出是或否的答案。 How should I go about this? 我应该怎么做?

Just use the command function and it will call a function whenever the button is clicked. 只需使用command功能,只要单击该按钮,它将调用一个功能。

import tkinter

tickets = 0

def ticket():
    tickets = 1
    print(tickets)

def twotickets():
    tickets = 2
    print(tickets)

def threetickets():
    tickets = 3
    print(tickets)

window = tkinter.Tk()

label = tkinter.Label(window, text="How many tickets would you like?")
button = tkinter.Button(window, text="One ticket", command=ticket)
button2 = tkinter.Button(window, text="Two tickets", command=twotickets)
button3 = tkinter.Button(window, text="Three tickets", command=threetickets)

label.pack()
button.pack()
button2.pack()
button3.pack()
window.mainloop()

You can have as many of these buttons as you'd like as long as you bind them to a function if you want them to do anything. 只要您希望它们执行任何操作,只要将它们绑定到函数,就可以根据需要使用任意数量的这些按钮。 Also, remember if you'd like to use this changed variable, declare it global where you'd like to use it. 另外,请记住,如果要使用此更改的变量,请在要使用它的位置全局声明它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM