简体   繁体   English

在tkinter中,如何访问在另一个窗口中创建的变量?

[英]In tkinter, how can I access variables created in one window in a different one?

I can't seem to figure out how to create or modify a variable in one window of my application and then later access it in another one. 我似乎无法弄清楚如何在我的应用程序的一个窗口中创建或修改变量,然后在另一个窗口中访问它。 Also, how can I retrieve the selected value on the spinboxes in the StartPage? 另外,如何在StartPage的Spinbox上检索选定的值?

Here is the code I'm using: 这是我正在使用的代码:

import tkinter as tk

TITLE_FONT = ("Helvetica", 18, "bold")

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        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, PageOne, PageTwo):
            frame = F(container, self)
            self.frames[F] = frame
            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, c):
        '''Show a frame for the given class'''
        frame = self.frames[c]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="CALCULO DE PRECIOS", font=TITLE_FONT)
        label.pack(side="top", fill="x", pady=10)

        test1 = tk.Spinbox(self, values=(1, 2, 4, 8))
        test1.pack()

        test2 = tk.Spinbox(self, values=(1, 2, 4, 8))
        test2.pack()

        button1 = tk.Button(self, width=20, text="Calculo Final",
                            command=lambda: controller.show_frame(PageOne))
        button2 = tk.Button(self, width=20, text="Calculo Actividades",
                            command=lambda: controller.show_frame(PageTwo))
        button1.pack()
        button2.pack()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="CALCULO FINAL", font=TITLE_FONT)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, width=20, text="Volver al menu principal",
                           command=lambda: controller.show_frame(StartPage))
        button.pack()




class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="CALCULO ACTIVIDADES", font=TITLE_FONT)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, width=20, text="Volver al menu principal",
                           command=lambda: controller.show_frame(StartPage))
        button.pack()


if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

Since each window you create, is an instance of a class that has a reference to the controller, variables may be passed between windows by setting a value on the controller. 由于您创建的每个窗口都是具有对控制器引用的类的实例,因此可以通过在控制器上设置一个值在窗口之间传递变量。

For example, in a window created from the PageOne , you can set a value on the controller like this: In init , make sure you store a reference to the controller in both classes PageOne and PageTwo : 例如,在从PageOne创建的窗口中,您可以像这样在控制器上设置一个值:在init ,确保将对控制器的引用存储在PageOnePageTwo类中:

self.controller = controller

At the point you want to pass a variable you can set it on the controller object: 在要传递变量时,可以在控制器对象上进行设置:

self.controller.value = "value"

In the window created from PageTwo , you can access this value like this: 在通过PageTwo创建的窗口中,您可以像这样访问此值:

value_from_other_window = self.controller.value

To answer your other question, to access the value from a spinbox, you need to have a reference to the spinbox object. 要回答您的另一个问题,要从旋转框访问值,您需要对旋转框对象进行引用。 I would suggest you keep these as instance variables of the classes PageOne and PageTwo : 我建议您将这些保留为PageOnePageTwo类的实例变量:

self.test1 = tk.Spinbox(self, values=(1, 2, 4, 8))

When you need to access the value, you can call: 需要访问值时,可以调用:

self.test1.get()

You probably shouldn't be having two classes PageOne and PageTwo as each of these seem to have exactly the same code, but for the label text. 您可能不应该拥有两个类PageOnePageTwo因为它们似乎都具有完全相同的代码,只是标签文本。 You could consider adding another parameter to init, which is the label text. 您可以考虑向init添加另一个参数,即标签文本。

I have modified your code to retrieve the selected values of the Spinbox in the StartPage class with the specificities of the spinbox widget, and to print the current values in the PageOne and PageTwo classes in the button callback: 我已修改您的代码,以获取具有Spinbox小部件特性的StartPage类中Spinbox的选定值,并在按钮回调中的PageOne和PageTwo类中输出当前值:

import tkinter as tk
TITLE_FONT = ("Helvetica", 18, "bold")
class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.varSpin1=1
        self.varSpin2=1

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(StartPage)

    def show_frame(self, c):
        '''Show a frame for the given class'''
        frame = self.frames[c]
        frame.tkraise()
        #print("spinbox values: %d %d"%(self.varSpin1,self.varSpin2))

class StartPage(tk.Frame):
    def setVarSpin1(self,v):
        self.controller.varSpin1=v
    def setVarSpin2(self,v):
        self.controller.varSpin2=v
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="CALCULO DE PRECIOS", font=TITLE_FONT)
        label.pack(side="top", fill="x", pady=10)
        self.controller=controller
        val1 = tk.IntVar()
        val2 = tk.IntVar()
        self.test1 = tk.Spinbox(self, values=(1,2,4,8), textvariable=val1,
                                command=lambda:self.setVarSpin1(val1.get())).pack()
        self.test2 = tk.Spinbox(self, values=(1,2,4,8), textvariable=val2,
                                command=lambda:self.setVarSpin2(val2.get())).pack()
        button1 = tk.Button(self, width=20, text="Calculo Final",
                            command=lambda: controller.show_frame(PageOne)).pack()
        button2 = tk.Button(self, width=20, text="Calculo Actividades",
                            command=lambda: controller.show_frame(PageTwo)).pack()

class PageOne(tk.Frame):
    def callback(self):
        print("PageOne: spinbox values: %d %d"%(self.controller.varSpin1,self.controller.varSpin2))
        self.controller.show_frame(StartPage)
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="CALCULO FINAL", font=TITLE_FONT)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, width=20, text="Volver al menu principal",
                           command=lambda:self.callback()).pack()
        self.controller=controller        

class PageTwo(tk.Frame):
    def callback(self):
        print("PageTwo: spinbox values: %d %d"%(self.controller.varSpin1,self.controller.varSpin2))
        self.controller.show_frame(StartPage)   
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="CALCULO ACTIVIDADES", font=TITLE_FONT)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, width=20, text="Volver al menu principal",
                           command=lambda:self.callback()).pack()
        self.controller=controller

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

暂无
暂无

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

相关问题 如何将变量从一个 Tkinter window 传递给另一个? - How can I pass variables from one Tkinter window to another? 如果我在一个 function 中创建了小部件,我如何使用 PythonE460F8BEA5A9F5118 在另一个 function 中访问它们 - If I created widgets in one function, how can I access them in another function using Python Tkinter? Python tkinter:如何确保在单击时仅创建一个子窗口,而不在每次单击按钮时创建一个新窗口? - Python tkinter: How can I ensure only ONE child window is created onclick and not a new window every time the button is clicked? 如何将这个 tkinter label 和字符串组合成一个 window? - How can I combine this tkinter label and string into one window? 如何将多个变量存储在一个文件中,并从另一个文件中访问这些变量? - How can I store many variables in one file, and access those variables from a different file? 如何使用 tkinter python 一键实现不同功能 - How can I have different functions in one button with tkinter python Python 2.7如何从存储在不同类中的列表访问由一个类创建的对象 - Python 2.7 How can I access objects created by one class from a list stored within a different class 我可以在一个Tkinter(tk.Tk)根窗口中使用两个不同的TTK主题吗? - Can I use two different TTK themes in one Tkinter (tk.Tk) root window? 我不能在一个 tkinter 窗口中使用两个框架 - I can't use two frames in one tkinter window 如何让导入的模块访问 tkinter 小部件和变量? - How can I have imported modules access tkinter widgets and variables?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM