首页 > 解决方案 > 我想将一个变量从一个类传递到另一个类,并使用 python 和 tkinter 在 Label 小部件中使用它

问题描述

我想将变量nstartpageto 传递给page1. 然后将变量放入一个名为 的标签小部件label_country中。我怎样才能做到这一点tkinter?我尝试通过类调用变量,我也使用了该n.get()方法。

import tkinter as tk
from tkinter import ttk

class tkinterApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self, height=1000, width=1000, bg="gray")
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.frames = {}
    
        for F in (StartPage, Page1):
            frame = F(container, self)
            self.frames[F] = frame
            frame.place(relx=0, rely=0, relwidth=1, relheight=1)
    
        self.show_frame(StartPage)
    
    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, bg="gray")
    
        style = ttk.Style()
        style.configure('W.TButton', foreground='black', background='white'
                        )
        button = ttk.Button(self, text="slect a country ", style='W.TButton',
                            command=lambda: [ controller.show_frame(Page1)])
        button.place(relx=0.66, rely=0.05, relwidth=0.2, relheight=0.07)
    
        ttk.Label(self, text="country slect:").place(relx=0.14, rely=0.05, relwidth=0.5, relheight=0.07)
    
        n = tk.StringVar()
    
        country_choice = ttk.Combobox(self, width=27, textvariable=n)
        country_choice["values"] = ([x for x in df["Country"].unique()])
        country_choice.place(relx=0.14, rely=0.05, relwidth=0.5, relheight=0.07)
        country_choice.current()
        text_box = tk.Text(self, height=28, width=30, bg="white")
        text_box.insert(tk.INSERT, "INFORMATIONT ABOUT THE PROGRAM")
        text_box.config(state="disabled")
        text_box.place(relx=0.14, rely=0.15, )

class Page1(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, bg="gray")
    
        label_country = tk.Label(self, text= StartPage.n, bg = "white")
        label_country.place(relx=0.795, rely=0.13, relwidth=0.0755, relheight=0.03)

app = tkinterApp()
app.mainloop()

标签: pythontkinter

解决方案


推荐阅读