代码:
import sys
from tkinter import *
credit = 0
coins = 0
choice = 0
credit1 = 0
coins = 0
prices = [200,150,160,50,90]
item = 0
i = 0
temp=0
n=0
choice1 = 0
choice2 = 0
credit1 = 0
coins = 0
prices = [200,150,160,50,90]
item = 0
i = 0
temp=0
n=0
choice1 = 0
choice2 = 0
def insert():
insert = Tk()
insert.geometry("450x250")
iLabel = Label(insert, text="Enter coins.[Press Buttons]").grid(row=1, column=1)
tenbutton = Button(insert, text="10p").grid(row=2, column=1)
twentybutton = Button(insert, text="20p").grid(row=3, column=1)
fiftybutton = Button(insert, text="50p").grid(row=4, column=1)
poundbutton = Button(insert, text="£1").grid(row=5, column=1)
我正在创建一个模拟自动售货机的程序。 我怎么告诉Python检查'如果按下了一个按钮? 在伪代码中它将是:
if tenbutton is pressed:
Add 10p to credit
我如何用Python编写#34;如果按下了十按钮"?提前谢谢。
答案 0 :(得分:4)
您可以将command
添加到将回调函数的Tkinter Button
小部件中:
def tenbuttonCallback():
global credit
credit += 10
tenbutton = Button(insert, text="10p", command=tenbuttonCallback)
tenbutton.grid(row=2, column=1)
答案 1 :(得分:4)
很简单,定义一个按钮按下后调用的功能。像这样:
def addCredit():
global credit
credit+=10
然后将这个简单的功能分配给你的按钮:
tenbutton = Button(insert, text="10p", command=addCredit).grid(row=2, column=1)
顺便说一句,你的代码在某个地方要求class
。使用如此多的全局变量通常是一种不好的做法。另一个挑剔是from tkinter import *
,它破坏了可读性。我建议import tkinter as tk
。
答案 2 :(得分:0)
from tkinter import *
import tkinter
import tkinter.messagebox
root = Tk()
def fun(arg):
if arg == 1:
tkinter.messagebox.showinfo("button 1", "button 1 used")
elif arg == 2:
tkinter.messagebox.showinfo("button 2", "button 2 used")
elif arg == 3:
tkinter.messagebox.showinfo("button 3", "button 3 used")
elif arg == 4:
tkinter.messagebox.showinfo("button 4", "button 4 used")
b1 = Button(root, text="Quit1", command=lambda: fun(1))
b1.pack()
b2 = Button(root, text="Quit2", command=lambda: fun(2))
b2.pack()
b3 = Button(root, text="Quit3", command=lambda: fun(3))
b3.pack()
b4 = Button(root, text="Quit4", command=lambda: fun(4))
b4.pack()
root.mainloop()