craig234
craig234

Reputation: 48

How to define a choice (symbol) from combobox widget as a (global) variable?

I would like to come directly to the point, so I will firstly just ask all my questions which I have.

  1. In Class Win1 I have a combobox, my question is: Is there a possibility to define the entry/chosen symbol as a variable and is there a possibility to define the variable as global, without having to redefine classes?

This is my second question, which is at the moment less relevant than the first one.

  1. When this code is running, first one window shows up, then a second one and so on. When turning this code into a software/app/..., will the software then also show one window than a second one or will everything be in one window?
import math
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
matplotlib.use('TkAgg')
#------------------------------------------------------------------------------
import tkinter
import tkinter as tk
from tkinter import ttk
import tkinter.font as tkFont
import tkinter.ttk as ttk
from tkinter import *
from tkinter.ttk import Combobox
#------------------------------------------------------------------------------
import numpy as np
#------------------------------------------------------------------------------
import pandas as pd
from pandas import DataFrame
from pandas.compat import StringIO
from pandas_datareader import data as web
#------------------------------------------------------------------------------
import yfinance as yf
#------------------------------------------------------------------------------
from statistics import mean
#------------------------------------------------------------------------------
import requests
#------------------------------------------------------------------------------
import time
from datetime import datetime
from datetime import date
from datetime import timedelta
import calendar
#------------------------------------------------------------------------------
import random
#------------------------------------------------------------------------------
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators
#------------------------------------------------------------------------------
import sys

from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
#------------------------------------------------------------------------------


#symbol = 'TSLA'



global_symbol = ""#None
#combobox = ""

def onSymbolSelected(self,event = None):
    global global_symbol
    global_symbol = self.combobox.get() # this assume combo is a property of Win1


def config_plot():
    fig, ax = plt.subplots()
    return(fig, ax)

class Win1:
    def __init__(self, master):
        self.master = master
        self.master.geometry("400x400")
        self.frame = tk.Frame(self.master)
        #symbol = Entry(root, text ='', bd=5)
        #userInput1 = StringVar(None)
        #self.master = Entry(root, textvariable=userInput1)
        #self.master.pack()
        SMI = ['ROG.SW','NOVN.SW','NESN.SW','SRAIL.SW','ABB','ADEN.SW','ALC.SW','CSGN.SW','GEBN.SW','GIVN.SW',
               'LONN.SW','CFR.SW','SIKA.SW','UHR.SW','SLHN.SW','SREN.SW','SCMN.SW','UBSG.SW','ZURN.SW']
        SMI.sort()

        NYSE = ['NYSE:MMM','NYSE:AXP','NYSE:AAPL','NYSE:BA','NYSE:CAT','NYSE:CVX','NYSE:CSCO','NYSE:KO','NYSE:DOW','NYSE:XOM',
                'NYSE:GS','NYSE:HD','NYSE:IBM','NYSE:INTC','NSYE:JNJ','NYSE:JPM','NYSE:MCD','NYSE:MRK','NYSE:MSFT','NYSE:NKE',
                'NYSE:PFE','NYSE:PG','NYSE:RTX','NYSE:TRV','NYSE:UNH','NYSE:VZ','NYSE:V','NYSE:WMT','NYSE:WBA','NYSE:DIS']
        NYSE.sort()

        DAX = ['ETR:ADS','ETR:ALV','ETR:BAS','ETR:BAYN','ETR:BEI','ETR:BMW','ETR:CON','ETR:1COV','ETR:DAI','ETR:DBK',
               'ETR:LHA','ETR:DPW','ETR:DTE','ETR:EOAN','ETR:FRE','ETR:FME','ETR:HEI','ETR:HEN3','ETR:IFX','ETR:MTX',
               'ETR:MUV2','ETR:RWE','ETR:SAP','ETR:SIE','ETR:VOW3','ETR:VNA','ETR:WDI']
        DAX.sort()

        Stockxx = []
        Stockxx.sort()

        symbol = ['ROG.SW','SMI','NYSE','DAX','Stockxx']
        symbol.sort()

        #symbol.current()

        #root= Tk()
        self.combobox = StringVar()
        self.combobox = ttk.Combobox(master, values = symbol)

        #def onSymbolSelected(self, Event = None):
         #   global global_symbol
          #  global_symbol = self.combobox.get()

        self.combobox.bind("<<ComboboxSelected>>", onSymbolSelected)#onSymbolSelected)
        #cb = ttk.Combobox(master, values = symbol)



        #print(var)
        # note that this is the StringVar ICUS, not the combobox ICUSTOMER.
        #label_var = tk.Label( textvariable= var) 
        #print(label_var)
        #label_ICustVar.grid(row = 3, column = 3)

        self.combobox.place(x=100, y=50)  

        button1 = Button(root, text="Click Here", fg = 'blue', width=20, command = lambda: self.new_window("2", Win2))
        button1.pack(side='bottom',padx=15,pady=15)
         # this assume combo is a property of Win1
        #self.butnew("Hauptfunktionen", "2", Win2)
        #self.butnew("Weitere Funktionen", "3", Win3)

        self.quit = tk.Button(self.frame, text = f"Close this window", command = self.close_window)
        self.quit.pack()

        self.frame.pack()
        print(symbol,"asfjöasldkjflödas")
        print(global_symbol,"ioöbajbo")
    def close_window(self):
        self.master.destroy()
    #def onSymbolSelected(self,event = None):
     #   global global_symbol
      #  global_symbol = self.combo.get() # this assume combo is a property of Win1

    def butnew(self, text, number, _class):
        tk.Button(self.frame, text = text, command= lambda: self.new_window(number, _class)).pack(side='left')

    def new_window(self, number, _class):
        self.new = tk.Toplevel(self.master)
        _class(self.new, number)





class Win2:
    def __init__(self, master, number):


        self.master = master
        self.master.geometry("1080x540")
        self.frame = tk.Frame(self.master)

        self.frame = Frame(self.master)
        self.fig, self.ax = config_plot()
        self.graphIndex = 0
        self.canvas = FigureCanvasTkAgg(self.fig, self.master)
        self.config_window()

        self.quit = tk.Button(self.frame, text = f"Close this window", command = self.close_window)
        self.quit.pack(side=LEFT)
        self.draw_graph_one()

        self.butnew("Weitere Funktionen", "3", Win3)

        self.frame.pack(expand=YES, fill=BOTH)


    def butnew(self, text, number, _class):
        tk.Button(self.frame, text = text, command= lambda: self.new_window(number, _class)).pack(side='left')

    def new_window(self, number, _class):
        self.new = tk.Toplevel(self.master)
        _class(self.new, number) 

    def draw_graph_one(self):
        ts = TimeSeries(key='YOUR_API_KEY',output_format='pandas')
        data1, meta_data1 = ts.get_monthly(symbol=global_symbol)
        df1 = data1['4. close']
        self.ax.clear()
        self.ax.plot(df1)
        self.ax.set(title='Historical Chart')
        self.canvas.draw()
#------------------------------------------------------------------------fertig
    def draw_graph_two(self):
        ts = TimeSeries(key='YOUR_API_KEY',output_format='pandas')
        data2, meta_data2 = ts.get_intraday(symbol=global_symbol, interval='1min', outputsize='compact')
        df2 = data2['4. close']
        self.ax.clear()
        self.ax.plot(df2)
        self.ax.set(title='Intraday')
        self.canvas.draw()
#------------------------------------------------------------------------fertig
    def draw_graph_three(self):
        ti = TechIndicators(key='YOUR_API_KEY',output_format='pandas')
        data3, meta_data3 = ti.get_bbands(symbol=global_symbol, interval='15min', time_period=30)
        df3 = data3

        ts = TimeSeries(key='YOUR_API_KEY',output_format='pandas')
        data2, meta_data2 = ts.get_intraday(symbol=global_symbol, interval='15min', outputsize='full')
        df2 = data2['4. close']

        self.ax.clear()
        self.ax.plot(df2, linestyle='-.')
        self.ax.plot(df3)
        self.ax.set(title='Bollinger Bands')
        self.canvas.draw()
#------------------------------------------------------------------------fertig
    def draw_graph_four(self):
        ti = TechIndicators(key='YOUR_API_KEY',output_format='pandas')
        data44, meta_data44 = ti.get_sma(symbol=global_symbol, interval='30min', time_period=60)
        df44 = data44

        ts = TimeSeries(key='YOUR_API_KEY',output_format='pandas')
        data1, meta_data1 = ts.get_intraday(symbol=global_symbol, interval='30min', outputsize='full')
        df1 = data1['4. close']

        self.ax.clear()
        self.ax.plot(df1)#, color='yellow')
        self.ax.plot(df44)#, color='black')
        self.ax.set(title='Simple Moving Average')
        self.canvas.draw()
#------------------------------------------------------------------------fertig
    def draw_graph_five(self):
        ts = TimeSeries(key='YOUR_API_KEY',output_format='pandas')
        data1, meta_data1 = ts.get_monthly(symbol=global_symbol)#, interval='1min', outputsize='full')
        df1 = data1['4. close']
        ts = TimeSeries(key='YOUR_API_KEY',output_format='pandas')
        dataG, meta_dataG = ts.get_monthly(symbol='UCITS ETF')#, interval='1min', outputsize='full')
        dG = dataG['4. close']
        self.ax.clear()
        self.ax.plot(df1)
        self.ax.plot(dG)
        self.ax.set(title='Comparision with Global Index')
        self.canvas.draw()
#------------------------------------------------------------------------------
    def draw_graph_six(self):
        ti = TechIndicators(key='YOUR_API_KEY',output_format='pandas')
        data23, meta_data23 = ti.get_cci(symbol=global_symbol, interval='30min', time_period=60)
        df23 = data23

        self.ax.clear()
        self.ax.plot(df23)
        self.ax.set(title='Commodity Channel Index')
        self.canvas.draw()
#------------------------------------------------------------------------fertig
    def draw_graph_seven(self):
        ti = TechIndicators(key='YOUR_API_KEY',output_format='pandas')
        data13, meta_data23 = ti.get_dx(symbol=global_symbol, interval='30min', time_period=60)
        df13 = data13

        self.ax.clear()
        self.ax.plot(df13)
        self.ax.set(title='Directional Movement Index')
        self.canvas.draw()
#------------------------------------------------------------------------------
    def draw_graph_eight(self):
        self.ax.clear()
        self.ax.plot()
        self.ax.set(title='Further Information')
        self.canvas.draw()
#------------------------------------------------------------------------------
    def draw_graph_nine(self):
        self.ax.clear()
        self.ax.plot()
        self.ax.set(title='Further Information')
        self.canvas.draw()


    def on_key_press(event):
        print("you pressed {}".format(event.key))
        key_press_handler(event, self.canvas, toolbar)


    def config_window(self):
        self.canvas.mpl_connect("key_press_event", self.on_key_press)
        toolbar = NavigationToolbar2Tk(self.canvas, self.master)
        toolbar.update()
        self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)


        self.button_switch1 = Button(self.master, text="Historical Chart", command=self.draw_graph_one)
        self.button_switch1.pack(side=LEFT)

        self.button_switch2 = Button(self.master, text="Intraday", command=self.draw_graph_two)
        self.button_switch2.pack(side=LEFT)

        self.button_switch3 = Button(self.master, text="Bollinger Bands", command=self.draw_graph_three)
        self.button_switch3.pack(side=LEFT)

        self.button_switch4 = Button(self.master, text="SMA", command=self.draw_graph_four)
        self.button_switch4.pack(side=LEFT)

        self.button_switch5 = Button(self.master, text="Comparison with Index", command=self.draw_graph_five)
        self.button_switch5.pack(side=LEFT)

        self.button_switch6 = Button(self.master, text="CCI", command=self.draw_graph_six)
        self.button_switch6.pack(side=LEFT)

        self.button_switch7 = Button(self.master, text="DX", command=self.draw_graph_seven)
        self.button_switch7.pack(side=LEFT)

        self.button_switch8 = Button(self.master, text="Technical Analysis", command=self.draw_graph_eight)
        self.button_switch8.pack(side=LEFT)

        self.button_switch9 = Button(self.master, text="Technical Analysis", command=self.draw_graph_nine)
        self.button_switch9.pack(side=LEFT)

    def close_window(self):
        self.master.destroy()

class Win3:
    def __init__(self, master, number):
        self.master = master
        self.master.geometry("1080x540")
        self.frame = tk.Frame(self.master)

        #self.frame = Frame(self.master)
        self.fig, self.ax = config_plot()
        self.graphIndex = 0
        self.canvas = FigureCanvasTkAgg(self.fig, self.master)
        self.config_window()

        self.quit = tk.Button(self.frame, text = f"Close this window", command = self.close_window)
        self.quit.pack(side=LEFT)
        self.frame.pack(expand=YES, fill=BOTH)

    def on_key_press(event):
        print("you pressed {}".format(event.key))
        key_press_handler(event, self.canvas, toolbar)


    def config_window(self):
        self.canvas.mpl_connect("key_press_event", self.on_key_press)
        toolbar = NavigationToolbar2Tk(self.canvas, self.master)
        toolbar.update()
        self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)

    def close_window(self):
        f.master.destroy()




root = tk.Tk()
app = Win1(root)
root.mainloop()

Sorry for asking so many questions, unfortunately I didn't completely understand the answers from my previous question. Thank you very much for your help. Ok, so I instead of opening a new thread, I decided just to expand my program directly here, since my new question is based on the old one. So I changed the program and my it doesn't work totally. The problem is that global_symbol doesn't change its value and I don't understand where the problem lies, I tried many things (leaving some lines, adding, etc) but none of them really worked. So does anyone of you guys know where the problem lies?

Upvotes: 1

Views: 122

Answers (1)

Jean-Marc Volle
Jean-Marc Volle

Reputation: 3333

For question 1/ What you can do (worst case) is add a callback to your combobox. This callback can then update a "global variable"

Callback setting on combobox :

self.combo = ttk.Combobox(master, values = symbol)
self.combo.bind("<<ComboboxSelected>>", onSymbolSelected)

symbol declaration outside of Win1

global_symbol = None

callback implementation in Win1

def onSymbolSelected(self,event = None)
    global global_symbol
    global_symbol = self.combo.get() # this assume combo is a property of Win1

Upvotes: 1

Related Questions