python-3.x tkinter使用类创建通用画布

vs91vp4v  于 2023-05-02  发布在  Python
关注(0)|答案(1)|浏览(153)

我知道我能做到。..

import tkinter as tk

root=tk.Tk()
root.geometry("800x600")
#Note if '=' is used, i.e. root.geometry=("800x600")
# then tkinter root(window) does NOT display full area

canv1=tk.Canvas(bg="green", height=150, width=200)
canv1.place(x=20,y=10)

root.mainloop()

理想情况下,我想做很多画布,当我学习类时,我想到这可以通过使用类来完成,这样我就可以更容易,更快速地示例化用户定义的画布。..canv2 = InstantCanvas(橙子,100,250)
我觉得这似乎是合理的:

import tkinter as tk

root=tk.Tk()
root.geometry("400x300")

class InstantCanvas():
    def __init__(self, background, height, width):
        self = self.tk.Canvas(background, height, width)
        # trying to achieve "my_user_canvas.

#Note if '=' is used, i.e. root.geometry=("800x600")
# then tkinter root(window) does NOT display full area

# Reference canvas, manually made
canv1=tk.Canvas(bg="green", height=150, width=200)
canv1.place(x=20,y=10)

canv2 = InstantCanvas("orange", 100, 250)
canv2.place(x=40,y=50)

root.mainloop()

但我得到一个错误。..AttributeError:“InstantCanvas”对象没有属性“tk”
所以我必须把import tkinter as tk放在类init函数中?看起来很奇怪和多余,但我还是试了。..

import tkinter as tk

root=tk.Tk()
root.geometry("400x300")

class InstantCanvas():
    import tkinter as tk
    def __init__(self, background, height, width):
        self = self.tk.Canvas(background, height, width)
        # trying to achieve "my_user_canvas.

#Note if '=' is used, i.e. root.geometry=("800x600")
# then tkinter root(window) does NOT display full area

# Reference canvas, manually made
canv1=tk.Canvas(bg="green", height=150, width=200)
canv1.place(x=20,y=10)

canv2 = InstantCanvas("orange", 100, 250)
canv2.place(x=40,y=50)

root.mainloop()

现在我得到了太多的参数错误,特别是Canvas。init()接受1到3个位置参数,但有4个被给出了,但我认为init有点忽略了 self 作为一个“硬”参数,但如果我把 self 去掉,那么我的init函数将无法“连接”到示例化的对象。那怎么做
关于为什么它不起作用以及如何使它起作用的反馈将不胜感激。Tq.

kgsdhlau

kgsdhlau1#

对于您的目的,似乎最好只是子类tk.Canvas,然后调用super()来初始化画布。

import tkinter as tk

class InstantCanvas(tk.Canvas):
    def __init__(self, background, height, width):
        super().__init__(bg=background, height=height, width=width)
        # trying to achieve "my_user_canvas.

root = tk.Tk()
root.geometry("400x300")

# Reference canvas, manually made
canv1 = tk.Canvas(bg="green", height=150, width=200)
canv1.place(x=20, y=10)

canv2 = InstantCanvas("orange", 100, 250)
canv2.place(x=40, y=50)

root.mainloop()

相关问题