【问题标题】:Python class with tkinter带有 tkinter 的 Python 类
【发布时间】:2021-10-05 18:54:16
【问题描述】:

我正在尝试学习 Python 中的类。

我用 tkinter 写了一点代码

from tkinter import *

class window():
    def __init__(self, size, title, ):
        self.size = size
        self.title = title

        window = Tk()
        window.geometry(self.size)
        window.title(self.title)

        print('a window has been created')

        window.mainloop()


    def button(self, window, text, x, y):

        self.window = window
        self.text = text
        self.x = x
        self.y = y

        button = Button(window, text=text).place(x=str(x), y=str(y))

但我收到错误消息:

self.tk = master.tk
AttributeError: 'window' object has no attribute 'tk'

【问题讨论】:

  • 类的定义方式很奇怪。你怎么称呼它?
  • 您需要包含您的完整代码,公司。生成错误消息的行来自哪里?
  • root = window('640x640', 'Root Window') root.button(root, 'test', "0", "0")

标签: python class tkinter


【解决方案1】:

你必须说这个函数或对象来自哪个文件

window = tkinter.Tk()

【讨论】:

  • 他还需要导入Button,更好的方法是像这样导入tkinter:import tkinter as tk然后改代码。
  • 是的,将代码更改为 window = tk.Tk() 他仍然需要提供文件名。即使是按钮
【解决方案2】:

我看不到你在哪里写self.tk 或者你在哪里打电话。可能在声明window时需要加上self.

像这样:

from tkinter import *

class window:
    def __init__(self, size, title, ):
        self.size = size
        self.title = title

        self.window = Tk()
        self.window.geometry(self.size)
        self.window.title(self.title)

        print('a window has been created')
        self.window.mainloop()


    def button(self, window, text, x, y):

        self.window = window
        self.text = text
        self.x = x
        self.y = y

        button = Button(window, text=text).place(x=str(x), y=str(y))

if __name__ == "__main__":
    worker = window("500x500", "nice title") # <-- You need to call the class.

(如果需要声明一个按钮,可以在__init__函数上面self.window.mainloop()上面加上这一行:self.button(self.window, "Title", 10, 20)

【讨论】:

    猜你喜欢
    • 2019-01-22
    • 2012-03-28
    • 2020-11-13
    • 2013-05-04
    • 2017-08-05
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多