Tkinter 网格管理器(类型错误)

Tkinter Grid Manager (TypeError)

我正在尝试将一组 16 张图片放入 tkinter 框架中。我创建了一个字典,将图像地址名称(存储在 imgbutton 中)映射为字典 imagedict 的键,其值是一个包含其在 tkinter 网格中的位置的字符串(例如第 0 列和 row=1 中的按钮将具有名称 backgroundpic5.jpg 和值“01”)。

每行4张图片,一共4行。与 imgbutton 等效的 PhotoImage 是 buttonphoto(使用 PIL 创建)。但是,当我尝试 运行 这个时,它告诉我 grid_configure 命令接受了 2 个参数,而我给出了 3 个(类型错误)

Pos=imagedict[imgbutton]
GridColumn=Pos[0]; GridRow=Pos[1]
Button= tk.Button(root, image=buttonphoto)
Button.grid(GridColumn, GridRow)
Button.pack()

错误语句,

Traceback (most recent call last):
  File "C:\Users\USER\Desktop\ComputerProject\Tester2Imagebg.py", line 44, in <module>
  Button.grid(GridColumn, GridRow)
  TypeError: grid_configure() takes at most 2 arguments (3 given)

谢谢:)

使用 grid() layout manager options 的正确语法:

 Button.grid(column = GridColumn, row = GridRow)

听听错误。它知道它在说什么……好吧,无论如何它都会告诉你一些事情。查找 Tkinter.Button.grid 的文档,它会告诉您。你需要做 Button.grid(column=GridColumn, row=GridRow)

你看,错误是对的。您给 Button.grid() 的参数太多了。使用 Button.grid(...) 实际上只是 tk.Button.grid(Button, ...) 的快捷方式,因此您总共提供了三个参数,但是 .grid() 需要一个按钮实例,cnf 和一些关键字参数。您使用 Button.grid(...) 而不是 tk.Button(...) 来提供按钮实例,但您提供了另外两个位置参数。您需要提供列号和行号作为关键字参数。