创建框架函数 python

creating Frame function python

我正在尝试编写一个创建框架的函数 这是代码:

from Tkinter import *
from ttk import *

def button(master, txt, line, col):
    new = Button(master, text=txt)
    new.grid(row=line, column =col, columnspan=2)

def frame(nb, txt):
    f = Frame(nb)
    nb.add(f, text = txt)

root = Tk()
nb = Notebook(root)
f1 = frame(nb, '1')
f2 = frame(nb, '2')

button(f1, '1', 0, 0)
nb.grid()
root.mainloop()

但是当我 运行 按钮的代码不在 f1 下时,它在 master window 本身中(见图): https://i.imgur.com/r3UbyLx.png

我怎样才能让它移动到 f1 下,当我在它上面时我看到按钮,当我在 f2 上时 window 中什么也没有?

你的 frame 函数是 returning None (由于它根本没有明确 returning 任何东西),所以 parent/master该按钮默认为根 window.

要修复它,让你的函数 return 框架:

def frame(nb, txt):
    ...
    return f