1

Code:

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) 

I am creating a program that simulates a vending machine. How would I tell Python to 'check' if A button has been pressed? In pseudocode it would be:

if tenbutton is pressed: Add 10p to credit 

How would I write in Python "if tenbutton is pressed"? Thank you in advance.

3 Answers 3

6

It's simple, define a function which will be called after button press. Like so:

def addCredit(): global credit credit+=10 

And then assign this simple function to your button:

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

By the way, your code is badly asking for a class somewhere. Using so many globals is generally a bad practice. Another nitpick is from tkinter import *, it destroys readability. I'd suggest import tkinter as tk.

Sign up to request clarification or add additional context in comments.

Comments

4

You can add a command to your Tkinter Button widget that will callback a function:

def tenbuttonCallback(): global credit credit += 10 tenbutton = Button(insert, text="10p", command=tenbuttonCallback) tenbutton.grid(row=2, column=1) 

See: http://effbot.org/tkinterbook/button.htm

Comments

4
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() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.