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.
SaveSave
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()
defcreate_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 exampledefbutton1_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 boxdefdo_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()
Learn how to get the unique id (conId) from Interactive brokers using a gui application. Every option has a different number since there are so many variations. The contract id (conid) is a number not a symbol, and this number you will need in order to trade options. For example the IBM 170 CALL option with an expiry on January 6, 2017 has a unique id number of 256910869. The number may be different on the next trading day. I am not sure if they stay the same from now, until the next day until they expire. You can search for a contract id number here: https://pennies.interactivebrokers.com/cstools/contract_info/v3.9/index.phpsee the code here To access a September 2016 $40 Call option on Netflix : I believe there is a data fee for options. You need to pay for a data feed for the options in order to request data through the API
conID = 3
# Contract ID
symbol = "NFLX"
# Netflix’s stock symbol
secType = "OPT"
# Security type is an Option (OPT)
expiry = "20170120"
# January 2017 Expiry format yyyymmdd
strike = 90
# $90.00 strike price
right = "CALL"
# Call option
multiplier = "100"
# multiplier 100 shares per contract for options
exchange = "SMART"
# Use IB’s Smart Order router to get the prices
currency = "USD"
# USD Currency
To access a June 2017 Crude Oil Futures contract set the properties:
conID = 2
# Contract Id
symbol = "CL"
# Crude Oil underlying symbol (CL)
secType = "FUT"
# Security type is an Future (FUT)
expiry = "20170120"
# January 20, 2017 Expiry third Friday of month
exchange = "NYMEX"
# Use IB’s Smart Order router to get the prices
To access a foreign exchange quote such as Euro/USD:
conID = 6
# Contract Id
symbol = "EUR"
# Euro underlying (base currency) symbol (EUR/USD quote)
Listbox Scroll bars tkinter Python Copy and paste the highlighted text into the section of your code where you create your widgets, and also add the x and yscrollcommands to the listbox parameters.
# Craig Hammond 2017
# www.sharpertradingimage.com# create scroll bars for your listboxself.scrollbar_V = Scrollbar(self)self.scrollbar_H = Scrollbar(self, orient=HORIZONTAL)self.scrollbar_V.grid(row=1, column=1, sticky=N+S+W)self.scrollbar_H.grid(row=5, column=0, sticky=N+E+S+W)# create listbox widget
self.listbox1 = Listbox(self, font=('', 12), width=15, height=10, yscrollcommand=self.scrollbar_V.set, xscrollcommand=self.scrollbar_H.set)
self.listbox1.bind('<<ListboxSelect>>', self.select_item)
self.listbox1.insert(1, 'FB')
self.listbox1.grid(row=1, column=0)
# add some text to the listbox
evil_corporations = ['EVIL CORPORATIONS y gobiernos', 'cranAAPLe', 'SBUckX', 'XOMobil',
'Any oil company that you care to name',
'OPECs', 'MSFaT', 'AMEXica', 'ALL COUNTRIES THAT DO NOT PROSECUTE THE BANKERS',
'most TRADING FIRMS', 'BUT NOT INTERACTIVE BROKERS BEST COMMISSIONS not as bad',
'banking cartels, the FED', 'las paisas que le gusta la guerra', 'foundations created by evil elitists']
for evil in evil_corporations:
self.listbox1.insert('end', evil)
# also needed for scroll barsself.scrollbar_V.config(command=self.listbox1.yview)self.scrollbar_H.config(command=self.listbox1.xview)
I am using the pack() Geometry Manager to place all of the widgets. I opted for the pack() Manager because it is ideal for placing widgets side by side or drop down position. Fortunately, in a text editor, I have all the widgets Placed next to each other or in descending order. It is therefore advantageous to the pack() Manager. We can do the same with the grid() manager also.
SaveSave
# Craig Hammond 2018import tkinter as tk
from tkinter import *
from tkinter import ttk
import re
classSampleTextApp(Frame):
def__init__(self, master, **kwargs):# this **kwargs is needed for the scroll bar
ttk.Frame.__init__(self, master)
self.file_name = None
self.grid()
self.create_widgets()
defcreate_widgets(self):
# font varialble to use with all widgets
my_font = ('', 18)
# add a text box for the line numbers
self.line_number_text = Text(self, font=my_font, width=4, padx=3, takefocus=0, border=0, background='yellow', state='disabled', wrap='none')
self.line_number_text.pack(side='left', fill='y')
# add the main text box widget here
self.main_text = Text(self, font=my_font, wrap='none')
self.main_text.bind('<KeyPress>', self.on_text_changed)
self.main_text.pack(expand='yes', fill='both')
# add a scroll bar for the main text widgetself.scroll_bar = Scrollbar(self.main_text)self.scroll_bar.pack(side='right', fill='y')# call the scroll bar functionsself.scroll_bar['command'] = self.on_scrollbarself.line_number_text['yscrollcommand'] = self.on_textscrollself.main_text['yscrollcommand'] = self.on_textscroll# this will update the line numbers any time you# press a key on the keyboard
self.main_text.bind('<Any-KeyPress>', self.on_text_changed)
self.main_text.focus_set()
defon_scrollbar(self, *args):self.line_number_text.yview(*args)self.main_text.yview(*args)defon_textscroll(self, *args):# Moves scrollbar and scrolls text widgets when the mouse wheel# is moved on the text widgetself.scroll_bar.set(*args)self.on_scrollbar('moveto', args[0])defon_text_changed(self, event=None):
self.update_line_numbers()
defget_line_numbers(self):
output = ''
row, col = self.main_text.index("end").split('.')
for i in range(1, int(row)):
output += str(i) + '\n'
return output
defupdate_line_numbers(self, event=None):
line_numbers = self.get_line_numbers()
# disables the text widget so the widget does not scroll
self.main_text.config(state='disabled')
self.line_number_text.config(state='normal')
self.line_number_text.delete('1.0', 'end')
self.line_number_text.insert('1.0', line_numbers)
self.line_number_text.config(state='disabled')
# returns the text widget back to normal
self.main_text.config(state='normal')
root = Tk()
PROGRAM_NAME = ' My Text Editor '
root.title(PROGRAM_NAME)
root.geometry("600x300")
app = SampleTextApp(root)
app.pack(fill='both', expand='yes')
app.mainloop()