代码:
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)
Run Code Online (Sandbox Code Playgroud)
我正在创建一个模拟自动售货机的程序。我如何告诉 Python “检查”是否按下了 A 按钮?在伪代码中,它将是:
if tenbutton is pressed:
Add 10p to credit
Run Code Online (Sandbox Code Playgroud)
“如果按下十个按钮”,我将如何用 Python 编写?先感谢您。
很简单,定义一个在按钮按下后将被调用的函数。像这样:
def addCredit():
global credit
credit+=10
Run Code Online (Sandbox Code Playgroud)
然后将这个简单的功能分配给您的按钮:
tenbutton = Button(insert, text="10p", command=addCredit).grid(row=2, column=1)
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您的代码严重要求class某个地方。使用这么多全局变量通常是一种不好的做法。另一个挑剔的是from tkinter import *,它破坏了可读性。我建议import tkinter as tk。