Sunday, 4 February 2018

Python Treeview delete rows

from tkinter import *
from tkinter import ttk

class Application(Frame):
    
    def __init__(self, master):
        """ Initialize the Frame"""
        ttk.Frame.__init__(self, master)
 
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.btnConnect = ttk.Button(self, text = "Search Symbol", command=self.search_symbol).grid(row=0, column=0, sticky=W)
        self.btnDisconnect = ttk.Button(self, text = "Add data", command=self.add_data).grid(row=0, column=1, sticky=W)
        self.btnCancelMktData = ttk.Button(self, text = 'Remove All', command=self.remove_all).grid(row=0, column=2, sticky=W)
        self.button_edit = Button(self, font=('',12), text="select row", width=7, command=self.add_data)
        self.button_edit.grid(row=0, column=4)
        
        # create Treeview widget to hold values in a table
        self.tv = ttk.Treeview(root)    

        # create Treeview 
        self.tv = ttk.Treeview(self,  height=8)
        self.tv['columns'] = ('id', 'symbol', 'price', 'trigger', 'shares', 'side', 'type', 'status', 'fill')
        self.tv.heading("#0", text='Time', anchor='w')
        self.tv.column("#0", stretch=NO, width=5, anchor="w")
        self.tv.heading('id', text='ID')
        self.tv.column('id', anchor='center', width=70)
        self.tv.heading('symbol', text='Symbol')
        self.tv.column('symbol', anchor='center', width=70)
        self.tv.heading('price', text='Price')
        self.tv.column('price', anchor='center', width=70)
        self.tv.heading('trigger', text='Trigger')
        self.tv.column('trigger', anchor='center', width=70)
        self.tv.heading('shares', text='Shares')
        self.tv.column('shares', anchor='center', width=100)
        self.tv.heading('side', text='Side')
        self.tv.column('side', anchor='center', width=70)
        self.tv.heading('type', text='Type')
        self.tv.column('type', anchor='center', width=70)
        self.tv.heading('status', text='Status')
        self.tv.column('status', anchor='center', width=100)
        self.tv.heading('fill', text='Fill')
        self.tv.column('fill', anchor='center', width=70)
        self.tv.bind('<ButtonRelease-1>', self.select_item) 
        self.tv.grid(row=1, column=0, columnspan=6, padx=5, pady=5)
        self.treeview = self.tv
##        self.ysb = ttk.Scrollbar(self, orient='vertical', command=self.tv.yview)
##        self.xsb = ttk.Scrollbar(self, orient='horizontal', command=self.tv.xview)
##        self.tv.configure(yscroll=self.ysb.set, xscroll=self.xsb.set)
##        self.ysb.grid(row=1, column=7, sticky='ns')
##        self.xsb.grid(row=2, column=0, sticky='ew')
        
        ttk.Style().configure("Treeview", font= ('', 11), background="#383838", 
        foreground="white", fieldbackground="yellow")

        self.tv.insert("","end",text = "Person",values = ("1254","MSFT","39.39", "", "0/200", "BUY", "LMT", "Filled", "39.39"), tags='hot')
        self.tv.insert("","end",text = "Animal",values = ("1255","MSFT","39.58", ".10", "0/200", "SELL", "TRAIL", "PreSubmitted", "0.00"), tags='cold')
        self.tv.insert("","end",text = "Name",values = ("1256","MSFT","39.58", "", "0/200", "SELL", "LMT", "Submitted", "0.00"), tags='pizza')
        self.tv.insert("","end",text = "Evil Corp",values = ("1258","NFLX","102.55", "", "0/300", "SELL", "LMT", "Submitted", "0.00"), tags='tacos')

    def remove_all(self):
        x = self.tv.get_children()
        print ('get_children values: ', x ,'\n')
        if x != '()': # checks if there is something in the first row
            for child in x:
                self.tv.delete(child)
                
    def search_symbol(self):
        pass

    def add_data(self):
        pass

    def select_item():
        pass

root = Tk()       
app = Application(root)
root.mainloop()


Save Save

Saturday, 3 February 2018

Scrolling 2 text widgets together

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.

Save Save

# Craig Hammond 2018

import tkinter as tk
from tkinter import *


from tkinter import ttk
import re

class SampleTextApp(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()

    def create_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 widget
        self.scroll_bar = Scrollbar(self.main_text)
        self.scroll_bar.pack(side='right', fill='y')

        # call the scroll bar functions
        self.scroll_bar['command'] = self.on_scrollbar
        self.line_number_text['yscrollcommand'] = self.on_textscroll
        self.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()
   
    def on_scrollbar(self, *args):
        self.line_number_text.yview(*args)
        self.main_text.yview(*args)
        
    def on_textscroll(self, *args):
        # Moves scrollbar and scrolls text widgets when the mouse wheel
        # is moved on the text widget
        self.scroll_bar.set(*args)
        self.on_scrollbar('moveto', args[0])
        
    def on_text_changed(self, event=None):
        self.update_line_numbers()
    
    def get_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

    def update_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()

Wednesday, 22 November 2017

Create an awesome mailing program in Python



# 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.com
import 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()

    def create_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

    def send_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 them
        for 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 time
            if 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 server
                print ('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()


Save Save Save

Saturday, 17 December 2016

IB TWS Trading Platform in Python 8 outsideRTH

IB TWS Trading Platform in Python 8 outsideRTH

In this tutorial you will add a check box to your gui form window that will allow you to trade after hours and pre-market.

Add this variable to hold the variable for the checkbox just above the create widgets function.

self.my_outsideRTH = False 
Add this to the end of the create_widgets(self): function
        # create a check button box for outside RTH
        self.chkOutsideRTH = Checkbutton(f1, font=('', 10),
                                         text='OutsideRTH', variable=varOutsideRTH)
        self.chkOutsideRTH.grid(row=9, column=6)
  Add highlighted text to the buy(self): function and the sell(self): function
  def buy(self):
        self.symbol = varSymbol.get()
        self.quantity = varQuantity.get()
        self.order_type = varOrderType.get()
        self.limit_price = varLimitPrice.get()
        self.my_outside = varOutsideRTH.get() # add here
        the_outsideRTH = 0
        if self.my_outside == True:
            the_outsideRTH = 1
        self.place_market_order(self.symbol, self.quantity, self.order_type,
                                True, self.limit_price, the_outsideRTH) # add here
    def sell(self):
        self.symbol = varSymbol.get()
        self.quantity = varQuantity.get()
        self.order_type = varOrderType.get()
        self.limit_price = varLimitPrice.get()
        self.my_outside = varOutsideRTH.get() # add here
        the_outsideRTH = 0
        if self.my_outside == True:
            the_outsideRTH = 1
        self.place_market_order(self.symbol, self.quantity, self.order_type,
                                False, self.limit_price, the_outsideRTH) # add here
Add the variable my_outsideRTH to the highlighted areas in the place_market_order() function as shown below.
    def place_market_order(self, symbol, quantity, order_type, is_buy, limit_price, my_outsideRTH): # add here
        print (symbol, quantity, order_type, is_buy, limit_price)
        contract = self.create_contract(symbol,
                                        'STK',
                                        'SMART',
                                        'NASDAQ',
                                        'USD')
 # tests if is buy or sell
        buysell = 'BUY' if is_buy else 'SELL'
        order = self.create_order(order_type, quantity, buysell, limit_price, my_outsideRTH)# add here
        self.tws_conn.placeOrder(self.order_id, contract, order)
        # increses the order id by one
        self.order_id += 1
Add the variable outsideRTH to the highlighted areas in the create_order() function as shown below.
    def create_order(self, order_type, quantity, action, limit_price, outside_Rth):    # add  outside_Rth 
        order = Order()
        order.m_orderType = order_type
        order.m_totalQuantity = quantity
        order.m_action = action
        order.m_lmtPrice = limit_price  
        order.m_outsideRth = outside_Rth                  # add order.m_outsideRth = outside_Rth 
        return order

Add this to the bottom where all the variables are for your window form widgets.
varOutsideRTH = StringVar(root, value=False) 


Pages: 1 2 3 4 5 6 7 8 9


Save

Saturday, 26 November 2016

Python Listbox delete text

In this video you will learn to delete a selected item in a listbox tkinter widget using Python3



# Craig Hammond 2016
from tkinter import 
from tkinter import ttk

class Application(Frame):
    
    def __init__(self, master):
        """ Initialize the Frame """
        ttk.Frame.__init__(self, master)
 
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        # create the button widgets
        self.btnAddSymbol = ttk.Button(self, text = "Add Symbol", command=self.add_symbol).grid(row=0, column=0, sticky=W)    
        self.tbEntry = Entry(self, font=('', 12), textvariable=varEntry).grid(row=0, column=1, sticky=W)
        self.btnDeleteSymbol = ttk.Button(self, text = 'Remove Symbol', command=self.delete_symbol).grid(row=0, column=2, sticky=W)

        # create listbox widget
        self.listbox1 = Listbox(self, font=('', 12))
        #self.listbox1.bind('<ButtonRelease-1>', self.select_item) # Don't use  it won't work
        self.listbox1.bind('<<ListboxSelect>>', self.select_item)
        self.listbox1.insert(1, 'EVIL')
        self.listbox1.insert(2, 'SBUX')
        self.listbox1.insert(3, 'FB')
        self.listbox1.grid(row=1, column=0)
        
    def add_symbol(self):
        to_add = varEntry.get() # gets text from textbox or Entry box
        # change 'end' to 0 to add it to the beginning
        self.listbox1.insert('end', to_add) # adds text to listbox 
        
    def select_item(self, event):
        pass
        
    def delete_symbol(self):
        current_selection = self.listbox1.curselection() # gets the position of the selected item
        # print (current_selection)
        self.listbox1.delete(current_selection) # deletes the selected item

root = Tk()
varEntry = StringVar(root, value="SCTY")
app = Application(root)
root.mainloop()

Thursday, 24 November 2016

Python Listbox Add Text


from tkinter import *
from tkinter import ttk

class Application(Frame):
    
    def __init__(self, master):
        """ Initialize the Frame"""
        ttk.Frame.__init__(self, master)
 
        self.grid()      
        self.create_widgets()

    def create_widgets(self):
        # create the button widgets
        self.btnAddSymbol = ttk.Button(self, text = "Add Symbol", command=self.add_symbol).grid(row=0, column=0, sticky=W)    
        self.tbEntry = Entry(self, font=('', 12), textvariable=varEntry).grid(row=0, column=1, sticky=W)
        self.btnDeleteSymbol = ttk.Button(self, text = 'Remove Symbol', command=self.delete_symbol).grid(row=0, column=2, sticky=W)

        # create listbox widget
        self.listbox1 = Listbox(self, font=('', 12))
        #self.listbox1.bind('<ButtonRelease-1>', self.select_item) # Don't use <Button-1> it won't work
        self.listbox1.bind('<<ListboxSelect>>', self.select_item)
        self.listbox1.insert(1, 'EVIL')
        self.listbox1.insert(2, 'SBUX')
        self.listbox1.insert(3, 'FB')
        self.listbox1.grid(row=1, column=0)
        
    def add_symbol(self):
        to_add = varEntry.get() # gets text from textbox or Entry box
        # change 'end' to 0 to add it to the beginning of the list
        self.listbox1.insert('end', to_add) # adds text to listbox 
        
    def select_item(self, event):
        pass
        
    def delete_symbol(self):
        pass

root = Tk()
varEntry = StringVar(root, value="SCTY")
app = Application(root)
root.mainloop()

Sunday, 13 November 2016

Python Tree view search cell contents

Python treeview search for cell value and change cell contents
# Craig Hammond 2016
from tkinter import *
from tkinter import ttk

class Application(Frame):
    
    def __init__(self, master):
        """ Initialize the Frame"""
        ttk.Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.btnConnect = ttk.Button(self, text = "Search Symbol", command=self.search_symbol).grid(row=0, column=0, sticky=W)
        self.btnDisconnect = ttk.Button(self, text = "Add data", command=self.add_data).grid(row=0, column=1, sticky=W)
        self.btnCancelMktData = ttk.Button(self, text = 'Remove All', command=self.remove_all).grid(row=0, column=2, sticky=W)
        self.button_edit = Button(self, font=('',12), text="select row", width=7, command=self.add_data)
        self.button_edit.grid(row=0, column=4)
        
        # create Treeview widget to hold values in a table
        self.tv = ttk.Treeview(root)    

        self.tv = ttk.Treeview(self,  height=8)
        self.tv['columns'] = ('id', 'symbol', 'price', 'trigger', 'shares', 'side', 'type', 'status', 'fill')
        self.tv.heading("#0", text='Time', anchor='w')
        self.tv.column("#0", stretch=NO, width=5, anchor="w")
        self.tv.heading('id', text='ID')
        self.tv.column('id', anchor='center', width=70)
        self.tv.heading('symbol', text='Symbol')
        self.tv.column('symbol', anchor='center', width=70)
        self.tv.heading('price', text='Price')
        self.tv.column('price', anchor='center', width=70)
        self.tv.heading('trigger', text='Trigger')
        self.tv.column('trigger', anchor='center', width=70)
        self.tv.heading('shares', text='Shares')
        self.tv.column('shares', anchor='center', width=130)
        self.tv.heading('side', text='Side')
        self.tv.column('side', anchor='center', width=70)
        self.tv.heading('type', text='Type')
        self.tv.column('type', anchor='center', width=70)
        self.tv.heading('status', text='Status')
        self.tv.column('status', anchor='center', width=100)
        self.tv.heading('fill', text='Fill')
        self.tv.column('fill', anchor='center', width=70)
        self.tv.bind('<ButtonRelease-1>', self.select_item) 
        self.tv.grid(row=1, column=0, columnspan=6, padx=5, pady=5)
        self.treeview = self.tv
##        self.ysb = ttk.Scrollbar(self, orient='vertical', command=self.tv.yview)
##        self.xsb = ttk.Scrollbar(self, orient='horizontal', command=self.tv.xview)
##        self.tv.configure(yscroll=self.ysb.set, xscroll=self.xsb.set)
##        self.ysb.grid(row=1, column=7, sticky='ns')
##        self.xsb.grid(row=2, column=0, sticky='ew')
        
        ttk.Style().configure("Treeview", font= ('', 11), background="black", 
        foreground="white", fieldbackground="yellow")

        self.tv.insert("","end",text = "Person",values = ("1254","MSFT","39.39", "", "0/200", "BUY", "LMT", "Filled", "39.39"), tags='hot')
        self.tv.insert("","end",text = "Animal",values = ("1255","MSFT","39.58", ".10", "0/200", "SELL", "TRAIL", "PreSubmitted", "0.00"), tags='cold')
        self.tv.insert("","end",text = "Name",values = ("1256","MSFT","39.58", "", "0/200", "SELL", "LMT", "Submitted", "0.00"), tags='pizza')
        self.tv.insert("","end",text = "Evil Corp",values = ("1258","NFLX","102.55", "", "0/300", "SELL", "LMT", "Submitted", "0.00"), tags='tacos')
        
    def select_item(self, a):   # added self and a
        pass

    def remove_all(self):
       pass
                
    def search_symbol(self):
        pass

    def add_data(self):
        x = self.tv.get_children() # variable to store the dictionary string
        if x != '()': # checks if there is something in the first row
            for item in x:
                values_Values = (self.tv.item(item)["values"]) # variable to hold the cell values
                tags_values = (self.tv.item(item)["tags"]) # variable to hold the tag values
                if values_Values[1] == "NFLX": # looks for value 1254
                    self.tv.item(item, values=(values_Values[0], # value from existing string
                                                            values_Values[1],
                                                            values_Values[2],
                                                            values_Values[3],
                                                            'Yippie Ki Evil Corp', # value to be changed 4th cell
                                                            values_Values[5],
                                                            values_Values[6],
                                                            values_Values[7],
                                                            values_Values[8]
                                                            ), tags=tags_values) # changes the tag value to bite
                    
                    
root = Tk()
app = Application(root)
root.mainloop()