您可以使用来自不同 python 文件的画布吗?

can you use canvases from different python files?

我有一个 canvas 设置了一个图像和文件 1.py 中的所有内容,就像这样

canvassomethingimg = ImageTk.PhotoImage(Image.open("bin/level1assets/scenes2/11.png"))
canvassomething = Canvas(root, width=1446, height=899, borderwidth=0, highlightthickness=0)
canvassomething.create_image(0, 0, anchor=NW, image=canvassomethingimg)

并想在 file2.py

中使用它
canvassoemthing.place(x=-1, y=0)

当然有代码可以让它像 root 和所有东西一样工作,我有它。但我需要从另一个文件开始使用 canvases。可能吗?

这取决于哪个文件是您程序的主要入口点。

  • 如果是file1.py,那么file2.py应该是可以在file1.py中使用的functions/classes的集合,使用你创建的canvas作为参数。

file2.py:

def place_canvas(canvas):
    canvas.place(x=-1, y=0)

file1.py

from file2 import place_canvas

canvassomethingimg = ImageTk.PhotoImage(Image.open("bin/level1assets/scenes2/11.png"))
canvassomething = Canvas(root, width=1446, height=899, borderwidth=0, highlightthickness=0)
canvassomething.create_image(0, 0, anchor=NW, image=canvassomethingimg)
...
place_canvas(canvassomething)
  • 现在如果相反(你只想初始化 file1 中的一些东西和 运行 file2 中的主要逻辑),你可以在 file1 中使用初始化函数 returns a Canvas 对象并在文件 2 中使用它:

file1.py

def init_canvas():
    ... # Probably the rest of your initialisation (like defining `root`)
    canvas_img = ImageTk.PhotoImage(Image.open("bin/level1assets/scenes2/11.png"))
    canvas = Canvas(root, width=1446, height=899, borderwidth=0, highlightthickness=0)
    canvas.create_image(0, 0, anchor=NW, image=canvassomethingimg)
    return canvas

file2.py

from file1 import init_canvas

canvassomething = init_canvas()
canvassomething.place(x=-1, y=0)