首页 > 解决方案 > 为什么我可以放置这个按钮的位置

问题描述

按钮不会转到我在运行时设置的位置,我能得到一点帮助吗?

import tkinter
newbw=tkinter.Tk()  


def hub():    
    newbw.destroy()
    newbw=tkinter.Tk()
    newbw.attributes('-fullscreen', True)
    a=tkinter.Button(newbw, text="demonfight", command=dfpre)
    b=tkinter.Button(newbw, text="shop", command=shop)
    c=tkinter.Button(newbw, text="train", command=trainhub)
    d=tkinter.Button(newbw, text="quit", command=end)
    d.place(x=20, y=20)
    a.pack()
    b.pack()
    c.pack()
    d.pack()

标签: pythontkinter

解决方案


有三个几何管理器:packgridplace。使用其中之一被称为mapping小部件。

网格不能混用。这是一个或另一个。 Place可以与packgrid混合使用,但它确实(在我看来)是最后的选择,因为placed小部件在自动调整大小时不会被外框检测到。因此,由于上述原因,您可以将packplace混合使用而不会出错。

一旦你map有了几何管理器,你就可以unmapremapd.place() places因此,您第一次调用d小部件。但是随后您的第二次调用将d.pack()覆盖place()然后packs是小部件。

因为默认为pack()side='top',所以您会看到四个小部件堆叠在一起, a在顶部,d在底部。

此外,您的应用程序无法正常工作,因为您创建了一个函数hub(),但您从未调用它。添加:

if __name__ == '__main__':
    hub()

到程序的底部。

因此,尽管您发布的代码不完整,但请尝试类似以下的操作:

import tkinter

def hub():    
    newbw=tkinter.Tk()
    newbw.attributes('-fullscreen', True)
    a=tkinter.Button(newbw, text="demonfight", command=dfpre)
    b=tkinter.Button(newbw, text="shop", command=shop)
    c=tkinter.Button(newbw, text="train", command=trainhub)
    d=tkinter.Button(newbw, text="quit", command=end)
    #  d.place(x=20, y=20)
    a.pack()
    b.pack()
    c.pack()
    d.pack()

if __name__ == '__main__':
    hub()

推荐阅读