0

私はpythonが初めてです。Python 3.7、Windows OS で作業しています。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 の値を取得しようとroot = Class1.main_window.rootしましたが、関数に root 属性がないというエラーが表示されました。

私の問題を解決するのを手伝ってください。

4

3 に答える 3

1

関数はルートを取得する必要があると思います

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

次にclass1で:

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

そして3番目:

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

===

Class1.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()

Class2.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()
于 2020-10-06T07:59:38.157 に答える
0

まず、Class2 のクラスの名前「this」に誤りがある可能性があります。「this」は現在のオブジェクト インスタンスの予約名だと思います。「class2」など、別のものに変更する必要があります。

次に、class1 で class2 をインスタンス化し、ルートを引数としてコンストラクターに渡す必要があります。そうして初めて、class2 で root を使用できます。

于 2020-10-06T07:57:07.247 に答える
0

クラス コンストラクターに引数を渡す例を次に示します。

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()
于 2020-10-06T08:31:26.567 に答える