Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

แอตทริบิวต์ 'tearoff' ใน Tkinter Menu ทำหน้าที่อะไร?

ด้วย Tkinter.Menu เราสามารถสร้างเมนูและซับเมนูได้ มีพร็อพเพอร์ตี้อื่นๆ ที่ใช้กับเมนูของ tkinter อีกด้วย

คุณสมบัติ Tearoff ทำให้เมนูในหน้าต่างสามารถ "ดึงถอน" (tearable) ได้ แอตทริบิวต์ tearoff รับค่า Boolean เพื่อแยกเมนูจากหน้าต่างหลักหรือหน้าต่างพาเรนต์ ด้วย tearoff เรามี 2 ตัวเลือก:

  • ถ้า tearoff=0 เมนูจะติดอยู่กับหน้าต่าง (ไม่สามารถดึงออกได้)

  • ถ้า tearoff=1 จะแสดงเส้นจุดว่าง "----" บนเมนู ซึ่งเราสามารถดึงเมนูออกจากหน้าต่างได้

ตัวอย่าง

# Importing the tkinter library
from tkinter import *

win = Tk()
win.title("Tearoff Example")
win.geometry("600x500")

# Define a Function for Menu Selection Event
def mytext():
    lab = Label(win, text="You have made a selection", font=('Helvetica', 20)).pack(pady=20)

# Create a Menubar
menu_bar = Menu(win)

# Make the menus non-tearable
file_menu = Menu(menu_bar, tearoff=0)

# Tearable Menu (uncomment to use)
# file_menu = Menu(menu_bar, tearoff=1)

file_menu.add_command(label="New", command=mytext)
# all file menu-items will be added here next
menu_bar.add_cascade(label='File', menu=file_menu)
win.config(menu=menu_bar)

mainloop()

ผลลัพธ์

การรันโค้ดข้างต้นจะสร้างหน้าต่างที่มีเมนู

สำหรับเมนูที่ไม่สามารถดึงออกได้ (tearoff=0) และเมนูที่ดึงออกได้ (tearoff=1) ผลลัพธ์จะเป็นดังนี้:

แอตทริบิวต์  tearoff  ใน Tkinter Menu ทำหน้าที่อะไร?

แอตทริบิวต์  tearoff  ใน Tkinter Menu ทำหน้าที่อะไร?