【问题标题】:Python - Tkinter: Window classPython - Tkinter:窗口类
【发布时间】:2015-01-27 08:00:06
【问题描述】:

如何在 tkinter 中创建一个带有类的窗口?

我知道root = Tk() 是执行此操作的标准方法,但如果我想创建一个在 python 中创建“窗口”的类,我可以稍后添加按钮给谁完成?

我从下面的代码中得到这个错误:

Traceback (most recent call last):
  File "C:/Users/euc/PycharmProjects/Skole/Shortcut/Gui2.py", line 26, in <module>
    b = Create_button(a)
  File "C:/Users/euc/PycharmProjects/Skole/Shortcut/Gui2.py", line 18, in __init__
    self.button = Button(window, text=text)
  File "C:\Python34\lib\tkinter\__init__.py", line 2161, in __init__
    Widget.__init__(self, master, 'button', cnf, kw)
  File "C:\Python34\lib\tkinter\__init__.py", line 2084, in __init__
    BaseWidget._setup(self, master, cnf)
  File "C:\Python34\lib\tkinter\__init__.py", line 2062, in _setup
    self.tk = master.tk
AttributeError: 'Create_window' object has no attribute 'tk'

我的代码:

from tkinter import *

class Create_window(): #Create a window
    win = Tk()
    def __init__(self):
        self = Tk()
        self.title("This is title Name")

class Create_button: # Create a button within the window
    text = "None"
    button_width = 15
    button_height = 10

    def __init__(self, window, text="null"):
        if text == "null": #Set text to none if none parameter is passed
            text = self.text

        self.button = Button(window, text=text)
        self.button.grid(row=0, column=0)



a = Create_window()  # Create window
b = Create_button(a) # Create button within Window

a.mainloop()

【问题讨论】:

  • 请注意,您在代码中声明了 2 个不同的 Tk()。赢 = Tk() 和自我 = Tk()。我听说这会导致很多问题。
  • 是的。不可取。这就是为什么我在我的回答中删除了不必要的并修改了 OP 的代码。
  • 我这样做了,希望如果我做了 a.win,它会起作用,但没有起作用。

标签: python class tkinter


【解决方案1】:

您可以继承Toplevel 来执行此操作。查看this 了解更多关于Toplevel 的信息。

我还对您的代码进行了一些清理和重组。比较您的代码和此代码,并注意为一些更好的做法所做的差异和更改。

注意类名约定而不是方法名约定。类名通常不以动词或动作词开头,因为本质上类是对象或名词。另一方面,函数和方法必须以动词或动作词开头。

您不需要使用类来为看起来可以放在单个函数中的东西创建按钮。

这是修改后的sn-p:

from tkinter import *

class MyWindow(Toplevel): #Create a window
    def __init__(self, master=None):
        Toplevel.__init__(self, master)
        self.title("This is title Name")


def create_button(frame, text="None"): # Create a button within the frame given
    button_width = 15
    button_height = 10

    frame.button = Button(frame, text=text)
    frame.button. configure(height=button_height, width=button_width)
    frame.button.grid(row=0, column=0)


app = Tk()
a = MyWindow(master=app)  # Create window
create_button(a) # Create button within Window

app.mainloop()

还请务必查看great tutorial,了解如何使用和继承 Toplevel 以创建对话框。

希望这会有所帮助。

【讨论】:

  • 这是一个巨大的帮助!尽其所能;)非常感谢@kartikg3 非常感谢:)
猜你喜欢
  • 2022-11-20
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
  • 2020-04-02
  • 2013-04-05
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
相关资源
最近更新 更多