tkinter网格管理器无法正确显示按钮

时间:2018-01-24 15:38:12

标签: python tkinter

我有一个带1个视频帧和5个按钮的应用。我希望视频帧在顶部,而按钮很好地排在一行中。

这是我的代码:

    self.root = tki.Tk()
    self.panel = None
    #create a button, that when pressed, will take the current
    #frame and save it to file
    btn= tki.Button(self.root, text="Snapshot!", command=self.takeSnapshot)
    btn.grid(sticky = tki.S)

    btnturnl= tki.Button(self.root, text="Left", command = self.EinsRechts)
    btnturnl.grid(sticky = tki.SW)

    btnturnl2= tki.Button(self.root, text="Two Left", command = self.ZweiRechts)
    btnturnl2.grid(sticky = tki.SW)

    btnturnr= tki.Button(self.root, text="Right", command = self.EinsLinks)
    btnturnr.grid(sticky = tki.SE)

    btnturnr2= tki.Button(self.root, text="Two Right", command = self.ZweiLinks)
    btnturnr2.grid(sticky = tki.SE)
    self.panel = tki.Label(image=image) #in this panel the video feed gets shown
    self.panel.image = image
    self.panel.grid(sticky = tki.N)

这就是它的真实面貌:

what am I doing wrong?

我不熟悉Tkinter,所以如果我错过了一个更适合我的功能,我很乐意改变我的代码。

如果您有任何问题,请随时询问并感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

您缺少实际的列和行参数:

http://effbot.org/tkinterbook/grid.htm#patterns

答案 1 :(得分:1)

以此示例来实现您的目标。使用rowcolumn就像excel工作表一样,这样您就可以将值增加到您想要的位置。

btn= tki.Button(self.root, text="Snapshot!", command=self.takeSnapshot)
btn.grid(row=1 , column=2, sticky = tki.S)

btnturnl= tki.Button(self.root, text="Left", command = self.EinsRechts)
btnturnl.grid(row=3 , column=5, sticky = tki.SW)

答案 2 :(得分:0)

替换:

btn.grid(sticky = tki.S)
...
btnturnl.grid(sticky = tki.SW)
...
btnturnl2.grid(sticky = tki.SW)
...
btnturnr.grid(sticky = tki.SE)
...
btnturnr2.grid(sticky = tki.SE)
...
self.panel.grid(sticky = tki.N)

使用:

btn.grid(row=1, column=0, sticky = tki.S)
...
btnturnl.grid(row=1, column=1, sticky = tki.SW)
...
btnturnl2.grid(row=1, column=2, sticky = tki.SW)
...
btnturnr.grid(row=1, column=3, sticky = tki.SE)
...
btnturnr2.grid(row=1, column=4, sticky = tki.SE)
...
self.panel.grid(row=0, column=0, columnspan=5, sticky = tki.N)

如果您未在row来电column来指定gridrow个号码,则默认为last_row_no + 1column0

在下面查看生成相同 GUI的代码段:

import tkinter as tk


root = tk.Tk()
label = tk.Label(root, text="Label")
button = tk.Button(root, text="Button")

label.grid()                            # implicit
button.grid()

root.mainloop()

与:

相同
import tkinter as tk


root = tk.Tk()
label = tk.Label(root, text="Label")
button = tk.Button(root, text="Button")

label.grid(row=0, column=0)             # explicit
button.grid(row=1, column=0)

root.mainloop()

建议明确,后者是更好的代码,引用python (import this)的禅:

"Explicit is better than implicit."