python - 为 tkinter 小部件创建一个类以调用默认属性
问题描述
我正在尝试在 Python3 中使用 tkinter 创建一个 GUI,它将有几个按钮,我不想每次都为所有这些按钮键入相同的属性,如下所示:
tkinter.Button(topFrame, font=("Ariel", 16), width=10, height=10,
fg="#ffffff", bg="#000000", text="Cake")
例如,fg
每个按钮上的bg
颜色和颜色size
都相同。每个按钮上唯一改变的是文本以及屏幕上的放置位置。
我对编程和 Python 很陌生,并且在我想创建一个新按钮时尝试重用代码。我想我错过了一些我在阅读时没有得到的课程的理解。
我想为每个按钮和不同的框架传递不同的文本,以便将其放置在 GUI 上的不同位置并使其他所有内容都相同。
到目前为止我的代码:
import tkinter
import tkinter.messagebox
window = tkinter.Tk()
#create default values for buttons
#frame and buttonText are the values passed to the class when making a new
#button
class myButtons:
def buttonLayout(self, frame, buttonText):
self.newButton=tkinter.Button(frame, font=("Ariel", 16),
width=10, height=10, fg=#ffffff,
bg=#000000, text=buttonText)
topFrame = tkinter.Frame(window)
topFrame.pack()
#create new button here and place in the frame called topFrame with the text
#"Cake" on it
buttonCake = myButtons.buttonLayout(topFrame, "Cake")
#position the new button in a certain cell using grid in topFrame
buttonCake.grid(row=1, column=0)
window.mainloop()
我尝试运行它时遇到的错误是:
TypeError: buttonLayout() missing 1 required positional argument: 'buttonText'
我很困惑,因为我正在传递"Cake"
并且错误说它丢失了。
感谢您指出init我不知道如何使用init来解决我的问题,但这和这里给出的答案有帮助。谢谢你。
解决方案
由于参数,您会收到错误self
。还有一个问题是您的代码没有创建MyButtons
该类的实例。
这是一个继承自Button
并自定义__init__
设置一些默认值的示例。
import tkinter
import tkinter.messagebox
window = tkinter.Tk()
#create default values for buttons
#frame and buttonText are the values passed to the class when making a new button
class MyButton(tkinter.Button):
def __init__(self, *args, **kwargs):
if not kwargs:
kwargs = dict()
kwargs['font'] = ("Arial", 16)
kwargs['width'] = 10,
kwargs['height'] = 10,
kwargs['fg'] = '#ffffff',
kwargs['bg'] = '#000000',
super().__init__(*args, **kwargs)
topFrame = tkinter.Frame(window)
topFrame.pack()
#create new button here and place in the frame called topFrame with the text "Cake" on it
buttonCake = MyButton(topFrame, text="Cake")
#position the new button in a certain cell using grid in topFrame
buttonCake.grid(row=1, column=0)
window.mainloop()
这会强制将您的默认值放入 Button。仅当您没有在调用中传递它们时,您才可以添加if
语句来定义它们,如下所示:
if not 'width' in kwargs:
kwargs['width'] = 10
推荐阅读
- java - SharedPreferences 在某些设备上提供默认值
- python - 如何在 Tensorflow 中构建具有输入和输出变量的可重用图?
- python - msys2/mingw64:pip:此模块不支持 VC 6.0
- android - 我们如何更改不同文件的菜单栏上的文本
- python - 如何检查地图是否在python中工作
- node.js - 将 API 放入平均堆栈应用程序但在邮递员中工作正常的问题
- elasticsearch - Elasticsearch 重新索引存储大小差异很大
- javascript - Angular 6 检测图表的变化
- qt - 将 QTextureMaterial 添加到自定义网格中
- javascript - 反应本机中未处理的承诺拒绝错误?