【发布时间】:2019-08-04 16:13:06
【问题描述】:
我正在尝试使用 Python3 中的 tkinter 创建一个 GUI,该 GUI 将有几个按钮,我不想每次都为所有按钮键入相同的属性,如下所示:
tkinter.Button(topFrame, font=("Ariel", 16), width=10, height=10,
fg="#ffffff", bg="#000000", text="Cake")
例如,fg、bg color 和 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”参数没有被传递给
buttonLayout函数——当你从一个对象调用一个实例方法时会隐式发生。buttonLayout应该是实例方法还是静态方法?它被定义为实例方法,但被称为静态方法。您应该创建一个myButton类的实例并从该实例调用buttonLayout函数。
标签: python class user-interface tkinter widget