Tkinter窗口配置不起作用

-2 投票
1 回答
43 浏览
提问于 2025-04-13 15:37

我正在尝试设置一个Tkinter窗口中的所有网格。

比如说:

import tkinter as Tk

window = Tk()
window.state('zoomed')
window.rowconfigure(0, weight=1, uniform='a')
winsdow.columnconfigure(0, weight=1, uniform='a')

window_home = Frame(window)
window_documents = Frame(window)
window_form = Frame(window)

这是我代码的基本结构。我想做的就是用一个循环来配置窗口home、窗口documents和窗口form,如下所示:

for frame in window:
  frame.rowconfigure(0, weight=1, uniform='a')
  frame.columnconfigure(0, weight=1, uniform='a')

但是在'for frame'后面的'in'这个词在vscode中似乎没有被激活。我觉得我在语法上可能有问题,但我不知道具体是什么。

有没有比我聪明的人(这可不稀奇)能帮我解决这个问题?

我甚至不知道该尝试什么。这个开发环境根本没有告诉我代码哪里出错了。

1 个回答

0

首先,你需要把第三行改成 window = tk.Tk(),我把导入的部分改成小写,因为这样命名更规范。

其次,为了让窗口显示出来,你必须在代码的最后加上 window.mainloop()

第三,window 不是可迭代的东西,它是一个 tk.Tk 类,所以你不能用 for 循环来遍历它。因为只有三个框架,我觉得没必要用循环,直接这样做就可以了:

import tkinter as tk

window = tk.Tk()
window.state('normal')
window.rowconfigure(0, weight=1, uniform='a')
window.columnconfigure(0, weight=1, uniform='a')

window_home = tk.Frame(window)
window_home.rowconfigure(0, weight=1, uniform='a')
window_home.columnconfigure(0, weight=1, uniform='a')

window_documents = tk.Frame(window)
window_documents.rowconfigure(0, weight=1, uniform='a')
window_documents.columnconfigure(0, weight=1, uniform='a')

window_form = tk.Frame(window)
window_form.rowconfigure(0, weight=1, uniform='a')
window_form.columnconfigure(0, weight=1, uniform='a')

window.mainloop()

如果你坚持要用 for 循环的话,你可以这样做:

frames = [window_home, window_documents, window_form]
for frame in frames:
    frame.rowconfigure(0, weight=1, uniform='a')
    frame.columnconfigure(0, weight=1, uniform='a')

撰写回答