2014-03-19 357 views
1

代码:检查一个按钮是否在python中被按下?

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'检查'A按钮是否被按下? 伪代码将是:

if tenbutton is pressed: 
    Add 10p to credit 

我怎么会用Python语言编写“如果按下tenbutton”?先谢谢你。

回答

4

您可以将command添加到您的Tkinter Button部件将回调函数:

def tenbuttonCallback(): 
    global credit 
    credit += 10 

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

参见:http://effbot.org/tkinterbook/button.htm

+0

哈哈我们必须google搜索同样的东西,并得到相同的结果:) – Dunno

+1

我每天都在使用Tkinter。不需要谷歌;) – atlasologist

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

+0

感谢您的帮助!它非常棒! @不知道 – PythonBeginner

相关问题