简体   繁体   English

是否有可能在 class 中为 Python GUI 定义全局变量?

[英]Is there a possibility to define a global variable inside a class for Python GUI?

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
import tkinter.font as tkFont
import tkinter.ttk as ttk
from tkinter import *
#------------------------------------------------------------------------------
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'




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

        button1 = Button(root, text="Click Here", fg = 'blue', width=20)#, command=self.new_window("2", Win2))
        button1.pack(side='bottom',padx=15,pady=15)

        self.butnew("Hauptfunktionen", "2", Win2)
        self.butnew("Weitere Funktionen", "3", Win3)

        self.frame.pack()

    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 config_plot():
    fig, ax = plt.subplots()
    return(fig, ax)


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.frame.pack(expand=YES, fill=BOTH)

    def draw_graph_one(self):
        ts = TimeSeries(key='YOUR_API_KEY',output_format='pandas')
        data1, meta_data1 = ts.get_monthly(symbol=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=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=symbol, interval='15min', time_period=30)
        df3 = data3

        ts = TimeSeries(key='YOUR_API_KEY',output_format='pandas')
        data2, meta_data2 = ts.get_intraday(symbol=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=symbol, interval='30min', time_period=60)
        df44 = data44

        ts = TimeSeries(key='YOUR_API_KEY',output_format='pandas')
        data1, meta_data1 = ts.get_intraday(symbol=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=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=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=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()
root = tk.Tk()
app = Win1(root)
root.mainloop()

This is just a part of my code.这只是我的代码的一部分。 My program consists of 3 windows, which are all similar built.我的程序由 3 个 windows 组成,它们都是类似的。 But I have to input a string (Entry...) and then this variable (symbol = Entry(....)) has to be valid through the whole program, inclusively other classes.但是我必须输入一个字符串 (Entry...),然后这个变量 (symbol = Entry(....)) 必须在整个程序中有效,包括其他类。 So my question is, how do I have to define the variable?所以我的问题是,我该如何定义变量? I already tried global symbol, which didn't work.我已经尝试过全局符号,但没有用。

If you make it a class variable:如果将其设为 class 变量:

class Win1:
    symbol = Entry(root, text ='', bd=5)

Then other code can access this by:然后其他代码可以通过以下方式访问它:

Win1.symbol

You could make a class which handles all windows, then put the symbol there, then pass the symbol as a parameter to all those windows.您可以制作一个 class 来处理所有 windows,然后将符号放在那里,然后将符号作为参数传递给所有这些 windows。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM