![](/img/trans.png)
[英]How do I set the Text in tkinter size to the size of the main window?
[英]How to set a tkinter window to a constant size
我正在用 tkinter 编写一个小游戏,简单地说,我被卡住了。
我有一个很好的起始菜单,其中有两个按钮和一个标签。
如果我只是创建框架一切都很好,它的大小为 500x500 像素
我希望在创建按钮和标签时背景不会改变,但无论我做什么,它都会适应大小。 这是我的代码:
import tkinter as tk
def startgame():
pass
mw = tk.Tk() #Here I tried (1)
mw.title('The game')
back = tk.Frame(master=mw, width=500, height=500, bg='black')
back.pack()
go = tk.Button(master=back, text='Start Game', bg='black', fg='red',
command=lambda:startgame()).pack()
close = tk.Button(master=back, text='Quit', bg='black', fg='red',
command=lambda:quit()).pack()
info = tk.Label(master=back, text='Made by me!', bg='red',
fg='black').pack()
mw.mainloop()
我已经在 stackoverflow 上搜索过,但没有得到任何有用的信息! 我发现只有一个问题与我的有点相似,但答案不起作用。 我试过这个:
(1) mw.resizable(width=False, height=False)
我无法想象这是什么问题,我真的很绝望。
您可以通过设置pack_propagate(0)
来关闭pack_propagate
在这里关闭pack_propagate
基本上是说不要让框架内的小部件控制它的大小。 所以你已经将它的宽度和高度设置为 500。关闭传播静止允许它是这个大小,而小部件不会改变框架的大小来填充它们各自的宽度/高度,这是正常情况下会发生的
要关闭调整根窗口的大小,您可以设置root.resizable(0, 0)
,其中分别允许在x
和y
方向上调整大小。
要将 maxsize 设置为 window,如另一个答案中所述,您可以设置maxsize
属性或minsize
尽管您可以只设置根窗口的几何形状,然后关闭调整大小。 更灵活一点。
每当您在小部件上设置grid
或pack
,它都会返回None
。 因此,如果您希望能够保留对小部件对象的引用,则不应将变量设置为正在调用grid
或pack
的小部件。 您应该将变量设置为小Widget(master, ....)
,然后在小部件上调用pack
或grid
。
import tkinter as tk
def startgame():
pass
mw = tk.Tk()
#If you have a large number of widgets, like it looks like you will for your
#game you can specify the attributes for all widgets simply like this.
mw.option_add("*Button.Background", "black")
mw.option_add("*Button.Foreground", "red")
mw.title('The game')
#You can set the geometry attribute to change the root windows size
mw.geometry("500x500") #You want the size of the app to be 500x500
mw.resizable(0, 0) #Don't allow resizing in the x or y direction
back = tk.Frame(master=mw,bg='black')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window
#Changed variables so you don't have these set to None from .pack()
go = tk.Button(master=back, text='Start Game', command=startgame)
go.pack()
close = tk.Button(master=back, text='Quit', command=mw.destroy)
close.pack()
info = tk.Label(master=back, text='Made by me!', bg='red', fg='black')
info.pack()
mw.mainloop()
如果您希望整个窗口具有特定大小,则可以使用geometry
命令为其指定所需大小。 这就是你真正需要做的。
例如:
mw.geometry("500x500")
但是,您还需要确保窗口内的小部件正确调整大小,因此更改添加框架的方式:
back.pack(fill="both", expand=True)
试试parent_window.maxsize(x,x);
设置最大尺寸。 即使您设置了背景等,它也不应该变大。
编辑:使用parent_window.minsize(x,x)
也将其设置为恒定大小!
您的问题有两种解决方案:
mw.geometry('500x500')
或
back.place(x = 0, y = 0, relwidth = 1, relheight = 1)
*应使用第二个选项代替back.pack()
这里是最简单的方法。
import tkinter as tk
root = tk.Tk()
root.geometry('200x200')
root.resizable(width=0, height=0)
root.mainloop()
我不认为有什么要说明的。 这很直接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.