简体   繁体   English

使用Tkinter在Python中放置按钮有任何帮助吗?

[英]Any help on placing buttons with Tkinter in Python?

UPDATE - I got it to work by using the .grid() function in Tkinter. 更新 -我通过在Tkinter中使用.grid()函数使其工作。 Thanks for all the help! 感谢您的所有帮助!

I would like to make a button that will center itself in the middle of the GUI in Tkinter, but I have tried using the place() function and also, the pack() function will not work. 我想创建一个按钮,使其在Tkinter的GUI中间居中,但是我尝试使用place()函数,而且pack()函数将不起作用。 Any tips or advice? 有任何提示或建议吗?

A section of my code: 我的代码的一部分:

restart = Button(tk, text = "Restart", command = restartGame)
    restart.pack()
    #The code to place the button in the middle goes here

I rarely ever recommend using place , but if you literally only have a single widget that you want to put in the center of some other widget, place is a really good choice: 我很少建议使用place ,但是如果您实际上只有一个小部件要放在其他小部件的中心,那么place是一个很好的选择:

restart.place(relx=.5, rely=.5, anchor="center")

relx sets the relative x coordinate to be the middle (it is a floating point value between 0.0 and 1.0) relx将相对x坐标设置为中间(它是0.0到1.0之间的浮点值)

rely sets the relative y coordinate to be the middle 依赖将相对y坐标设置为中间

anchor specifies that the center of the widget should be at the x/y coordinate 指定窗口小部件的中心应在x / y坐标上

I assume you mean centering the button at the middle of the top/bottom. 我假设您的意思是将按钮居中放在顶部/底部中间。

You can use .pack(side = "bottom") to place the button at the bottom (middle) of the Tk window. 您可以使用.pack(side = "bottom")将按钮放置在Tk窗口的底部(中间)。

Using side = , you can define it as top, bottom, left, or right. 使用side = ,可以将其定义为上,下,左或右。

So this means that your code would look like: 因此,这意味着您的代码将如下所示:

restart = Button(tk, text = "Restart", command = restartGame)
restart.pack(side = "bottom")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM