【发布时间】: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,它会起作用,但没有起作用。