การใช้งาน Python GUI (Tkinter) : Tkinter Dropdown Menu (เมนูเลือกแบบ Dropdown)

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

มุมมองที่ขยายได้ กระทู้แนะนำ: การใช้งาน Python GUI (Tkinter) : Tkinter Dropdown Menu (เมนูเลือกแบบ Dropdown)

การใช้งาน Python GUI (Tkinter) : Tkinter Dropdown Menu (เมนูเลือกแบบ Dropdown)

โดย Jom07 » 16/03/2018 5:12 pm

การใช้งาน Python GUI (Tkinter) : Tkinter Dropdown Menu (เมนูเลือกแบบ Dropdown)

การทำงานภาษา Python มีฟังก์ชันต่าง ๆ ให้เลือกนำมาใช้ในการใช้งานได้อย่างเหมาะสม ทำงานร่วมกับโมดูลต่าง ๆ ที่สามารถดึงมาใช้งานร่วมกันได้ เพราะ Python ไม่ยึดติดกับแพลตฟอร์ม โดยจะพูดถึง GUI Tkinter ที่เป็นโมดูลอินเตอร์เฟซของ Python การทำงานหลักคือ สร้างหน้าต่างหน้าโปรแกรมขึ้นมาและภายในโปรแกรมผู้ใช้งานสามารถออกแบบได้อย่างเหมาะสม โดยจะมายกตัวอย่างการทำ Dropdown Menu

Dropdown Menu เป็นการสร้างเมนูขึ้นมาที่สามารถเลือกรายการในเมนูเดียว การทำงานนี้จะช่วยให้ลดการทำงานของโปรแกรม และง่ายต่อการนำไปใช้มากขึ้นโดยจะยกตัวอย่าง เช่น

การสร้างเมนู Dropdown Menu การเลือกภาษาโปรแกรม โดยมีเมนู 4 เมนูคือ Python ,Java, C++, C เมื่อกดเลือกเมนู โปรแกรมจะเก็บค่าการเลือกเข้าไป

ตัวอย่าง

โค้ด: เลือกทั้งหมด

from Tkinter import *
from ttk import *

root = Tk()
root.title("Dropdown Menu")
mainframe = Frame(root)
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
mainframe.pack(pady=100, padx=100)

tkvar = StringVar(root)

choices = ['Python','Java', 'C++', 'C']


popupMenu = OptionMenu(mainframe, tkvar, choices[1], *choices)
Label(mainframe, text="Choose a Language").grid(row=1, column=1)
popupMenu.grid(row=2, column=1)
tkvar.set('Python')

def change_dropdown(*args):
    print(tkvar.get())

tkvar.trace('w', change_dropdown)

root.mainloop()

ผลรัน
รูปภาพ

เมื่อเลือกเมนู
รูปภาพ

บทความที่เกี่ยวข้อง:
บทเรียน Python GUI
บทเรียน Python
VDO Tutorial - Python
บทเรียน Python Tensorflow

ข้างบน