首页 > 解决方案 > 为什么 tkinter 框架与使用网格方法的 Tk 窗口大小不同?

问题描述

我可能在这里很昏暗,但我不明白为什么在调整窗口大小和使用 Grid 方法时ttk.Frame,这个简单脚本中的小部件没有随窗口一起增长?Tk我不希望ttk.Label默认情况下带有图像的窗口会调整大小。但是,当窗口大于给定方法rowconfigurecolumnconfigure使用的标签时,我希望在标签周围看到粉红色(框架的背景颜色)。我的错误在哪里?

#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-

import tkinter as tk
import tkinter.ttk as ttk
from PIL import Image, ImageTk 

IMAGE = './images/test.jpg'


class App( ttk.Frame ):

    def __init__( self, master, **kwargs ):
        self.master = master

        super().__init__( master, style='app.TFrame', **kwargs  )

        photo = ImageTk.PhotoImage( Image.open( IMAGE ) )
        self.screen = ttk.Label( self, image=photo, style='app.TLabel' )
        self.screen.image = photo
        self.screen.grid( row=0, column=0, sticky='nsew' )


def init_ttkStyle():
    '''Initialize ttk widget styles.'''
    s = ttk.Style()            
    s.configure( 'app.TFrame', background='pink' )
    s.configure( 'app.TLabel', background='cyan', borderwidth=10, relief='ridge' )
    return s


def main():
    ROOT = tk.Tk()
    appStyle = init_ttkStyle()
    app = App( ROOT )
    app.grid( row=0, column=0, sticky='nsew' )  # ?
    app.columnconfigure( 0, weight=1 )          # ?
    app.rowconfigure( 0, weight=1 )             # ?
    #app.pack( expand=1, fill='both' )            #this works
    ROOT.mainloop()


if __name__ == "__main__":
    main()

标签: tkinter

解决方案


app是一个Frame小部件。当您在小部件上使用rowconfigure和时,它将按照您的规范进行网格化,但窗口不会。它适用于 的情况,因为它已被明确告知和完整的窗口。columnconfigureFrameroot.packexpandfillroot

要使其以类似的方式工作,请执行rowconfigureand columnconfigureon root


推荐阅读