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)
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()
# Craig Hammond 2017 YouTube channel bingazingas
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
# smtp.mail.yahoo.comimport time
from tkinter import *
from tkinter import ttk
import math
class Application(Frame):
""" Gui Application """def__init__(self, master):
""" initialize the Frame """
ttk.Frame.__init__(self, master)
self.grid()
self.create_widgets()
defcreate_widgets(self):
myfont = ('', 14, 'bold')
# row 0#create first button
self.btnConnect = Button(self, font=myfont, text = "Send Mail", bg='red', fg='white', command=self.send_mail).grid(row=0, column=0, sticky=W)
# row 1# create label for To:
self.label1 = Label(self, font=myfont, text='To: ').grid(row=1, column=0, pady=10, padx=10, sticky=E)
# create combo box for the address
self.cbToEmail = ttk.Combobox(self, font=myfont, width=40, textvariable=varTo)
self.cbToEmail['values'] = ('info@evil_corp.com', 'admin@yahoos.com', 'bobhatesthat@yahoo.com', 'juggernaut@gmail.com')
self.cbToEmail.grid(row=1, column=1, pady=10, padx=10)
# row 2# create label from
self.label2 = Label(self, font=myfont, text='From: ').grid(row=2, column=0, pady=10, padx=10, sticky=E)
# create combo box for the address
self.cbFromEmail = ttk.Combobox(self, font=myfont, width=40, textvariable=varFrom)
self.cbFromEmail['values'] = ('info@yahhoo.com',
'juggernaut@gmail.com',
'evil_corp@yahoo.com')
self.cbFromEmail.grid(row=2, column=1, pady=10, padx=10)
# row 3# create label list of email addresses
self.label3 = Label(self, font=myfont, text='Subject: ').grid(row=3, column=0, pady=10, padx=10, sticky=E)
# create combo box for the address
self.cbSubject = ttk.Combobox(self, font=myfont, width=40, textvariable=varSubject)
self.cbSubject['values'] = ('check out my latest update from my website', 'Webist has been updated')
self.cbSubject.grid(row=3, column=1, pady=10, padx=10)
# row 4# create label list of email addresses
self.label2 = Label(self, font=myfont, text='Address list name: ').grid(row=4, column=0, pady=10, padx=10, sticky=E)
# create combo box for the address
self.cbEmail_List = ttk.Combobox(self, font=myfont, width=40, textvariable=varEmail_List)
self.cbEmail_List['values'] = ('adresses_email.txt',
'Test_adresses_email.txt')
self.cbEmail_List.grid(row=4, column=1, pady=10, padx=10)
# row 5# create text box to hold the text for the letter
self.text = Text(self, font=('', 12), width=90, height=25)
self.text.grid(row=5, column = 0, columnspan=2, padx=5, pady=5, sticky='nsew')
self.scrollb = Scrollbar(self, command=self.text.yview)
self.scrollb.grid(row=5, rowspan=8, column=2, columnspan=2, pady=10, sticky='nse')
self.text['yscrollcommand'] = self.scrollb.set
defsend_mail(self):
from_address = varFrom.get() # get the address from the combobox who is sending the email example: 'sender_name@yahoo.com'
to_address = varTo.get() # get the address from the combobox for example: 'receiver_name@gmail.com'
file_to_open = varEmail_List.get()# get address text file from combobox on form
address_text = open(file_to_open,'r') # read the file
my_addresses = address_text.readlines() # read each line in text file
address_text.close() # close text file
text_Letter = self.text.get('1.0', END) # select all text in the listbox
counter = 1 # create a varialbe to increase an integer# loop through all the addresses and print themfor line in my_addresses:
print (counter, line)
counter +=1
subject_text = varSubject.get() # gets the contents of the combo box for the subject line
username = 'username@yahoo.com'# use your email address as the username
password = 'password'# password used to login to your email account
b=1 # create a counter set it to start at 1# how many email addresses to process
list_length = len(my_addresses)
t = list_length
print ('How many in the list', list_length)
msg = MIMEMultipart()
msg['From'] = from_address
msg['To'] = to_address
msg['Subject'] = subject_text
msg.attach(MIMEText(text_Letter))
server = smtplib.SMTP('smtp.mail.yahoo.com') # for gmail use: smtp.gmail.com
server.ehlo()
server.starttls()
server.ehlo()
server.login(username, password)
for atoaddress in my_addresses: # loop through each email address
ti = t % 12 # divide number by 12 send 12 at a timeif ti == 0: # if when you divide the number by 12 you get zero
server.sendmail(from_address,atoaddress,msg.as_string())
print (b, ' sent ', atoaddress) # print the address that you sent the mail to
time.sleep(2)
server.quit() # quit or close the serverprint ('it_quit')
time.sleep(8) # sleeps for 8 seconds
msg = MIMEMultipart() # re-connects and continues the main loop
msg['From'] = from_address
msg['To'] = to_address
msg['Subject'] = subject_text
msg.attach(MIMEText(text_Letter))
server = smtplib.SMTP('smtp.mail.yahoo.com') # for gmail use: smtp.gmail.com
server.ehlo()
server.starttls()
server.ehlo()
server.login(username, password)
b+=1
t-=1
else:
server.sendmail(from_address,atoaddress,msg.as_string())
print (b, ' sent ', atoaddress)
b+=1
t-=1
time.sleep(6)
server.quit()
print ('Done')
root = Tk()
root.title("email program in Python please donate")
root.geometry("840x625")
"""root.bind("", keydown)
root.bind("", keyup)"""
root.attributes("-topmost", True)
varTo = StringVar(root, value='to_address@gmail.com')
varFrom = StringVar(root, value='from_address@yahoo.com')
varText_Letter = StringVar()
varSubject = StringVar(root, value='Latest update from my website')
varEmail_List = StringVar(root, value='adresses_email.txt')
app = Application(root)
root.mainloop()
IB TWS Trading Platform in Python 3 part 7 - profit and loss
In this tutorial lesson you will add labels and textboxes to hold the unrealized, realized, and total profit and loss
add code to calculate the marked profit and loss for both a long position and a short position
Add these variables to your project
self.unrealized = 0 # used in monitor position
self.realized = 0 # used in monitor position
self.unrealized_pnl = 0
self.realized_pnl = 0
self.marked_pnl = 0
Add this to the bottom of the create_widgets() function
add this code to the bottom of the cbSymbol_onEnter() function
they set the text boxes for Position, average price, unrealized, realized, and marked to zero, also the 2 variables realized_pnl, and marked_pnl to zero
In this tutorial you will understand more about what goes into the code to request historical data for certain trading instruments. Check out the other properties for Options, Futures, and Forex at the end of the page. In the video example we will request data for stocks. This only works with Interactive Brokers Paste this call to a function at the end of the connect_to_tws function (The highlighted text in yellow below)
# make sure this is included in the connect_to_tws functionself.register_callback_functions()
Paste this code after the connect_to_tws function and make sure all your indents are correct
defcontract_creation(self):
self.listbox1.delete(0,END) # clears contents of the listbox
self.tws_conn.cancelHistoricalData(5) #cancels historical data
mySymbol = varSymbol.get() # get the symbol from the combobox
contract = self.create_contract(mySymbol,
'STK', # security STK = stock 'SMART', # exchange'NASDAQ',# primary exchange'USD') # currency
now = strftime('%Y%m%d %H:%M:%S', localtime(int(time())))
duration = varDuration.get() # get the duration ie. 1 D, 1 M, 1 Y
bar_size = varBarSize.get() # get the bar size ie. 5 mins, 2 mins, 1 day
self.tws_conn.reqHistoricalData(tickerId = 5, # contract number can be any number
contract=contract, # contract detail from above
endDateTime=now, # end date and time
durationStr=duration,
barSizeSetting=bar_size,
whatToShow='TRADES', # what to show ie. MIDPOINT, BID, ASK,
useRTH=1, # Regular trading hours 1 = RTH, 0 = all data
formatDate=1) # 1 = 20161021 09:30:00 2 = Unix time (Epoch)defregister_callback_functions(self):
# Assign server messages handling function.
self.tws_conn.registerAll(self.server_handler)
# Assign error handling function.
self.tws_conn.register(self.error_handler, 'Error')
deferror_handler(self, msg):
if msg.typeName == 'error'and msg.id != -1:
print ('Server Error:', msg)
defserver_handler(self, msg):
if msg.typeName == 'historicalData':
hd_date = msg.date
hd_open = msg.open
hd_high = msg.high
hd_low = msg.low
hd_close = msg.close
hd_volume = msg.volume
str_date = str(hd_date)
str_open = str(hd_open)
str_high = str(hd_high)
str_low = str(hd_low)
str_close = str(hd_close)
str_volume = str(hd_volume)
# creates a string containing date, open, high, low, close, volume
priceData2 = hd_date+","+str_open+","+str_high+","+str_low+","+str_close+","+str_volume
if'finished'in hd_date:
passelse:
str_data = hd_date, hd_open, hd_high, hd_low, hd_close, hd_volume
print (str_data) # prints info to the Python shell
self.listbox1.insert(END, priceData2) # adds info to the listboxelif msg.typeName == "error"and msg.id != -1:
returndef create_contract(self, symbol, sec_type, exch, prim_exch, curr):
contract = Contract()
contract.m_symbol = symbol
contract.m_secType = sec_type
contract.m_exchange = exch
contract.m_primaryExch = prim_exch
contract.m_currency = curr
return contract
Interactive Brokers API identifies a financial instrument using an object class named contract.
The properties for contract are as follows:
Property
Description
conId
Contract id for the financial instrument.
symbol
Stock symbol or symbol for Options or Futures
secType
Type of instrument: Stock=STK, Option=OPT, Future=FUT, etc.
expiry
used with Options or Futures: The expiration date format YYYYMMDD
strike
Options: The Options Strike Price
right
Options: The Options “PUT” or “CALL”
multiplier
Contract multiplier for Futures or Options "100"
exchange
Destination of order or requested. “SMART” = IB smart order router
primaryExchange
Primary listing exchange where the instrument trades. NYSE, NASDAQ, AMEX, BATS, ARCA, etc.
currency
Currency of the exchange USD or GBP or CAD or EUR, etc.
http://interactivebrokers.github.io/tws-api/classIBApi_1_1Contract.html#gsc.tab=0 Examples, before a data request is made or before an order is submitted, an object of class contract will be created and its attributes will be populated with appropriate values used to identify the financial instrument. For example, to access market data for Netflix stock, set the properties:
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 20, 2017 Expiry 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)