Skip to main content
 首页 » 编程设计

python之检查是否在 python 中按下了按钮

2025年05月04日1052php

代码:

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 

“如果按下 tenbutton”,我将如何用 Python 编写?提前谢谢你。

请您参考如下方法:

很简单,定义一个在按下按钮后调用的函数。像这样:

def addCredit(): 
    global credit 
    credit+=10 

然后将这个简单的功能分配给您的按钮:

tenbutton = Button(insert, text="10p", command=addCredit).grid(row=2, column=1) 

顺便说一句,您的代码在某处严重要求类。使用如此多的全局变量通常是一种不好的做法。另一个挑剔的是 from tkinter import *,它破坏了可读性。我建议 import tkinter as tk。