【发布时间】:2021-08-07 02:46:24
【问题描述】:
我在措辞上遇到了问题,所以让我解释一下。我正在学习使用面向对象编程作为项目的一部分,所以我决定从创建用于创建窗口的类和放置在窗口上的按钮开始(标签等。稍后也会出现)。换句话说,我希望能够将按钮放在“Window1”上,而无需在类中指定“Window1”(而是使用 CreateButton(values) 传递它。到目前为止,这是我的代码,并得到了帮助。 PS.在我尝试windowname参数之前它应该如何运行,并且我手动将窗口设置为home_window,但我似乎无法让windowname参数正确传递。
import tkinter as tk
from tkinter import ttk
home_window = tk.Tk()
home_window.title("Rota System")
home_window.geometry("600x600")
def thankyou():
print ("Thank you very much")
class CreateWindow():
def __init__(self, name, title, geometry):
self.name = name
self.title = title
self.geometry = geometry
name = tk.Tk()
name.title(title)
name.geometry(geometry)
class CreateButton():
def __init__(self, name, width, height, x, y, font, size, text, command, windowname):
#I want to be able to place the button on any window I want, not just home_window
self.name = name
self.width = width
self.height = height
self.x = x
self.y = y
self.font = font
self.size = size
self.text = text
self.command = command
self.windowname = windowname
name = tk.Button(windowname, text=text, command=command)
name.config(font=(font, size))
name.place(x=x, y=y, height=height, width=width)
CreateWindow("Test", "Test", "900x600")
CreateButton("Test","200","200","0","0","Courier",10,"Test",thankyou, "Test")
【问题讨论】:
-
你为什么不从
tk.Button继承?还是tk.Frame? -
顺便说一句,如果不是从任何东西继承,那些
()括号是不必要的,只需使用class ClassName:,如果你要继承然后使用class ClassName(InheritFrom):并且不要忘记在@ 987654327@ 方法使用super().__init__()或InheritFrom.__init__(self)(但也许与self相反) -
当您在 Tkinter 中创建任何小部件时,您必须将
parent设置为第一个参数 - 这样它就知道在哪里显示它。你应该对你的类做同样的事情 -win = CreateWindow(...)和CreateButton(win, ...)但是你应该继承类CreateWindow(tk.Tk)和CreateButton(tk.Button)来获得它。或者您应该创建使用return name的函数create_window()、create_button(),因为您的代码更适合函数。并且带有单词create的名称也很适合函数。