Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách đặt kích thước cố định (constant size) cho cửa sổ Tkinter?

Cửa sổ Tkinter đôi khi tự resize theo widget. Để cố định kích thước, dùng 3 phương pháp:

  • pack_propagate(True/False): ngăn widget resize frame.
  • resizable(x,y): khóa resize cửa sổ (0,0 = không resize).
  • pack(fill, expand): fill="both", expand=1 để widget lấp đầy kích thước geometry.

Tất cả widget bên trong sẽ không làm thay đổi kích thước cửa sổ.

Ví dụ

from tkinter import *

win = Tk()
win.geometry("700x300")
win.resizable(0,0)  # Khóa resize cửa sổ

label = Label(win, text="Select an option", font=('Times New Roman',12))
label.pack_propagate(0)  # Ngăn label resize frame
label.pack(fill="both", expand=1)

def quit():
    win.destroy()

b1 = Button(win, text="Continue")
b1.pack_propagate(0)
b1.pack(fill="both", expand=1)

b2 = Button(win, command=quit, text="Quit")
b2.pack_propagate(0)
b2.pack(fill="both", expand=1)

win.mainloop()

Kết quả

Cửa sổ cố định kích thước, không resize được.

Cách đặt kích thước cố định (constant size) cho cửa sổ Tkinter?