简体   繁体   English

Python - 从另一个 class 访问局部变量

[英]Python - accessing a local variable from another class

I have tried to condense the code down as much as possible to make it clear what I am asking...我试图尽可能地压缩代码以明确我在问什么......

I have a variable called chosen_name , determined in a class called booking_frame , that I would like to access in the calendar_frame class.我有一个名为 selected_name 的变量,在名为chosen_namebooking_frame中确定,我想在calendar_frame class 中访问它。

Therefore, it would be obvious for calendar_frame to inherit the attributes of booking_frame - however, I believe (I'm probably completely wrong lol) that calendar_frame has to inherit the characteristics of Frame so that the whole program functions correctly.因此, calendar_frame继承booking_frame的属性是很明显的——但是,我相信(我可能完全错了,lol) calendar_frame必须继承Frame的特性,以便整个程序正常运行。

The reason that calendar_frame is a completely separate class is so that it can appear as a different frame. calendar_frame是一个完全独立的 class 的原因是它可以显示为不同的框架。

Extremely grateful for any help given:)非常感谢提供的任何帮助:)


# import tkinter modules
from tkinter import *
from tkinter import ttk
import tkinter.font as tkFont
from PIL import ImageTk, Image
from tkcalendar import *



# define self
class tkinterApp(Tk):

    def __init__(self,*args, **kwargs):

        Tk.__init__(self, *args, **kwargs)

        # creating a container
        container = Frame(self)
        container.pack(side = "top", fill = "both", expand = True)

        container.grid_rowconfigure(0, weight = 1)
        container.grid_columnconfigure(0, weight = 1)

        # initialising frames to an empty array
        self.frames = {}

        menu_bar = Menu(container)
        main_menu = Menu(menu_bar)

        menu_bar.add_cascade(label="Main Menu", menu=main_menu)
        main_menu.add_command(label="Welcome page", command=lambda: self.show_frame(welcome_frame))
        main_menu.add_command(label="Book a vehicle", command=lambda: self.show_frame(booking_frame))
        main_menu.add_command(label="Register as new user", command=lambda: self.show_frame(register_frame))

        Tk.config(self, menu=menu_bar)

        for F in (welcome_frame, booking_frame, register_frame, calendar_frame):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row = 0, column = 0, sticky = "nsew")

        self.show_frame(welcome_frame)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()


class welcome_frame(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        welcome = Label(self, text="Hello, please use the menu above to navigate the interface")
        welcome.grid(row=0, column=4, padx=10, pady=10)

class register_frame(Frame):

    def __init__(self, parent, controller):

        Frame.__init__(self, parent)

        register_label = Label(self, text="New user - enter your details below to use the Collyer's car park.")
        register_label.grid()


class booking_frame(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        chosen_name = "Steve"


class calendar_frame(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

    print(booking_frame.chosen_name)


app = tkinterApp()
app.geometry("1000x800")
app.title("Collyer's Car Park")
app.mainloop()

First you need to change local variable chosen_name to instance variable self.chosen_name inside booking_frame class, otherwise it cannot be accessed outside the class:首先需要在booking_frame class中将局部变量chosen_name改为实例变量self.chosen_name ,否则在booking_frame之外无法访问:

class booking_frame(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        self.chosen_name = "Steve"  # changed to instance variable

Then you can access it via controller.frames[booking_frame].chosen_name inside calendar_frame class:然后你可以通过controller.frames[booking_frame].chosen_namecalendar_frame class 中访问它:

class calendar_frame(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        print(controller.frames[booking_frame].chosen_name)

Inheritance is to model relationships of objects which behave the same ("IS A" relationship). Inheritance 与行为相同的对象的 model 关系(“IS A”关系)。 It is not meant to share data between objects.它并不意味着在对象之间共享数据。

A possible solution to your problem is to use a third object, that would be shared between booking_frame and calendar_frame .您的问题的一个可能解决方案是使用第三个 object,它将在booking_framecalendar_frame之间共享。

This object can be a Python dictionary for example;例如,这个 object 可以是 Python 字典; you can pass it to all your "frame" objects, or you can maybe decide to have it global (not very academic, for sure, but quick and dirty):你可以将它传递给你所有的“框架”对象,或者你可以决定让它全局化(当然不是很学术,但又快又脏):

GLOBAL_STATE = {}

class booking_frame(Frame):
    ...
    GLOBAL_STATE["chosen_name"] = "Steve"

class calendar_frame(Frame):
    ...
    print(GLOBAL_STATE.get("chosen_name"))

I hope you can see now how you can refactor your code to share data between those objects.我希望您现在可以看到如何重构代码以在这些对象之间共享数据。

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

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