【问题标题】:How am I suppose to get the width and height of a Frame in Python我想如何在 Python 中获取 Frame 的宽度和高度
【发布时间】:2022-01-03 20:14:25
【问题描述】:

在我的 python 代码中,我试图使按钮的宽度与它所在的框架的宽度相同。调整窗口大小时,框架的宽度会发生变化。我试过Widget['width']Widget.winfo_width() 但他们都给了我错误。 我的代码:

from tkinter import *

root = Tk()
root.geometry('750x500')
root.minsize(750, 500)


# Frames
Screen = Frame(root, height=500, width=500, bg='pink').grid(row=0, column=0, sticky='nsew', rowspan=4)
root.grid_columnconfigure(0, weight=3)
Buttons = Frame(root, height=500, width=100, bg="blue").grid(row=0, column=1, sticky='nsew', rowspan=4, columnspan=2)
root.grid_columnconfigure(2, weight=1)
root.grid_rowconfigure(3, weight=1)

# Buttons
UpgradeBtn = Button(Buttons, text="Upgrades")
UpgradeBtn.grid(row=0, column=1, columnspan=2)
WallBreakBtn = Button(Buttons, text="Wall Breaking")
WallBreakBtn.grid(row=1, column=1, columnspan=2)


root.mainloop()

你能帮帮我吗?

【问题讨论】:

  • 我在代码的第一行也有from tkinter import * 顺便说一句
  • 这是一种不好的做法,但你知道你可以edit你的问题在那里更改信息
  • 您可以将按钮配置为增长而无需获取宽度。你知道吗?

标签: python-3.x tkinter


【解决方案1】:

.grid 方法返回None,因此您的原始代码中的ScreenButtons 都是None,而不是小部件。在第二个语句中运行 .grid 意味着 ScreenButtons 将具有 winfo_XXX 方法。

from tkinter import *
root = Tk()

root.geometry('750x500')
root.minsize(750, 500)
# Frames
Screen = Frame(root, height=500, width=500, bg='pink')
Screen.grid(row=0, column=0, sticky='nsew', rowspan=4) # Change
root.grid_columnconfigure(0, weight=3)
Buttons = Frame(root, height=500, width=100, bg="blue")
Buttons.grid(row=0, column=1, sticky='nsew', rowspan=4, columnspan=2) # Change
root.grid_columnconfigure(2, weight=1)
root.grid_rowconfigure(3, weight=1)

# New function
def on_upgrade():
    print(Screen.winfo_width(), Screen.winfo_height())

# Buttons
UpgradeBtn = Button(Buttons, text=" w x h ", command = on_upgrade ) # Change
UpgradeBtn.grid(row=0, column=1, columnspan=2)
WallBreakBtn = Button(Buttons, text="Wall Breaking")
WallBreakBtn.grid(row=1, column=1, columnspan=2)

root.mainloop()

这会将屏幕的宽度和高度打印到控制台。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-12
    • 2014-05-01
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 2011-09-25
    • 2012-10-10
    相关资源
    最近更新 更多