簡體   English   中英

如何將變量值從一個文件中的一個類傳遞到另一個文件中的另一個類 python tkinter

[英]How to pass variable value from one class in one file to another class in another file python tkinter

我是python的新手。 在 python 3.7,windows 操作系統上工作。 假設我創建了一個名為Class1.py的文件,其中

import tkinter as tk
import Class2
class main_window:
    def openanotherwin():
        Class2.this.now()
    def create():
        root = tk.Tk()
        button1 = tk.Button(root, text="Open another window", command = openanotherwin )
        button1.pack()
        root.mainloop()

現在我的Class2.py包含:

import tkinter as tk
class this():
    def now():
        new = tk.Toplevel(root)  #Error displayed: root is not defined
        lb = tk.Label(new, text = "Hello")
        lb.pack()
        new.mainloop()

我的Main.py包含:

import Class1
Class1.main_window.create()

顯示的錯誤是: root is not defined in Class2.py 我試過root = Class1.main_window.root來引入 root 的值,但它顯示函數沒有屬性 root 的錯誤。

請幫我解決我的問題。

我認為功能需要獲得root權限

 def now(root): 
    new = tk.Toplevel(root)  #Error displayed: root is not defined

然后在 class1 中:

def openanotherwin(root):
    Class2.this.now(root)

第三:

button1 = tk.Button(root, text="Open another window", command=lambda: main_window.openanotherwin(root) )

===

類1.py

import tkinter as tk
import Class2
class main_window:
def openanotherwin(root):
    Class2.this.now(root)
    def create():
        root = tk.Tk()
button1 = tk.Button(root, text="Open another window", command=lambda: main_window.openanotherwin(root) )
        button1.pack()
        root.mainloop()

類2.py

import tkinter as tk
class this():
def now(root): 
    new = tk.Toplevel(root)  #Error displayed: root is not defined
        lb = tk.Label(new, text = "Hello")
        lb.pack()
        new.mainloop()

首先,Class2 中類的名稱“this”可能存在錯誤。 我猜“this”是當前對象實例的保留名稱。 您應該將其更改為其他內容,例如“class2”

然后你應該在你的 class1 中實例化 class2 並將 root 作為參數傳遞給構造函數。 只有這樣,您才能在 class2 中使用 root。

這是將參數傳遞給類構造函數的示例:

class DemoClass:
    num = 101

    # parameterized constructor
    def __init__(self, data):
        self.num = data

    # a method
    def read_number(self):
        print(self.num)


# creating object of the class
# this will invoke parameterized constructor
obj = DemoClass(55)

# calling the instance method using the object obj
obj.read_number()

# creating another object of the class
obj2 = DemoClass(66)

# calling the instance method using the object obj
obj2.read_number()

暫無
暫無

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

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