Sunday, 4 February 2018

Python Button Tkinter passing arguments

Python tkinter button widget passing arguments.  In these examples I will show you several ways you can pass values, variables, arguments to a function. You will also learn how to add a right mouse click as well as the left mouse click.  

Save Save
Here is the code to start the tutorial and follow along
from tkinter import *
from tkinter import ttk

class Application(Frame):
    
    """ A GUI application """

    def __init__(self, master):
        """ Initialize the Frame"""
        ttk.Frame.__init__(self, master)

        self.grid()
        self.create_widgets()

    def create_widgets(self):
        # create a normal button
        self.button1 = Button(root, font=('', 16, 'bold'), text='.22 Cents', command=self.do_something)
        self.button1.grid(row=0, column=0, pady=5, padx=5)

        # create a text box (Entry box) to hold the value of the click event
        self.tbValue = Entry(root, font=('', 16, 'bold'), textvariable=varEntryValue).grid(row=1, column=2, pady=5, padx=5)

        # create a text box (Entry box) to hold a average price
        self.tbSet = Entry(root, font=('', 16, 'bold'), textvariable=varAvgPrice).grid(row=1, column=1, pady=5, padx=5)
        
    # button 1 example
    def button1_Click(event, arg):
        average_Price = varAvgPrice.get() # gets a value from the first Entry box
        c = float(average_Price) + arg # adds the value from the ttk .22 button to the first entry box value
        c = round(c, 2) # round off c to 2 decimal places
        varEntryValue.set(c) # sets the value in the second Entry box

    def do_something(self):
        varEntryValue.set('Hello, Hola, Bonjour')    

root = Tk()

root.title("Button Examples in Python")
root.geometry("790x850")
root.attributes("-topmost", True)
varEntryValue = StringVar()
varAvgPrice = StringVar(root, value='105.00')

app = Application(root)

root.mainloop()



No comments:

Post a Comment