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

這只是我的代碼的一部分。 我的程序由 3 個 windows 組成,它們都是類似的。 但是我必須輸入一個字符串 (Entry...),然后這個變量 (symbol = Entry(....)) 必須在整個程序中有效,包括其他類。 所以我的問題是,我該如何定義變量? 我已經嘗試過全局符號,但沒有用。

如果將其設為 class 變量:

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

然后其他代碼可以通過以下方式訪問它:

Win1.symbol

您可以制作一個 class 來處理所有 windows,然后將符號放在那里,然后將符號作為參數傳遞給所有這些 windows。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM