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

เพิ่มสไตล์ให้กับปุ่ม Python tkinter


Tkinter รองรับการสร้างโปรแกรม GUI โดยใช้ python เป็นอย่างดี นำเสนอวิธีต่างๆ ในการใส่สไตล์ให้กับปุ่มบนผืนผ้าใบ Tkinter ตามแบบอักษร ขนาด สี ฯลฯ ในบทความนี้ เราจะมาดูวิธีการใช้สไตล์กับปุ่มเฉพาะหรือปุ่มทั้งหมดโดยทั่วไปบนผืนผ้าใบ

การใช้งานกับปุ่มเฉพาะ

ให้พิจารณากรณีที่เรามีปุ่มสองปุ่มในแคนวาส และเราต้องการใช้สไตล์บางอย่างกับปุ่มแรกเท่านั้น เราใช้ W.TButton เป็นส่วนหนึ่งของการกำหนดค่าพร้อมกับแบบอักษรและสีพื้นหน้า

ตัวอย่าง

from tkinter import *
from tkinter.ttk import *

# Set the canvas
canv = Tk()
canv.geometry('200x150')

#Create style object
sto = Style()

#configure style
sto.configure('W.TButton', font= ('Arial', 10, 'underline'),
foreground='Green')

#Button with style
btns = Button(canv, text='Welcome !',
      style='W.TButton',
      command=canv.destroy)
btns.grid(row=0, column=1, padx=50)

#Button without style
btnns = Button(canv, text='Click to Start !', command=None)
btnns.grid(row = 1, column = 1, pady = 10, padx = 50)

canv.mainloop()

ผลลัพธ์

การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -

เพิ่มสไตล์ให้กับปุ่ม Python tkinter

นำไปใช้กับปุ่มทั้งหมด

เป็นการกำหนดค่าที่คล้ายคลึงกันด้านบน ยกเว้นว่ามีปุ่ม Tbutton เป็นสไตล์ ซึ่งจะนำไปใช้กับปุ่มทั้งหมดบนผ้าใบโดยอัตโนมัติ

ตัวอย่าง

from tkinter import *
from tkinter.ttk import *

canv = Tk()
canv.geometry('200x150')

#Create style object
sto = Style()

#configure style
sto.configure('TButton', font=
('calibri', 10, 'bold', 'underline'),
foreground='Green')
# button 1
btns = Button(canv, text='Welcome !',
      style='TButton',
      command=canv.destroy)

btns.grid(row=0, column=1, padx=50)

# button 2
btnns = Button(canv, text='Click to start !', command=None)
btnns.grid(row=1, column=1, pady=10, padx=50)

canv.mainloop()

ผลลัพธ์

การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -

เพิ่มสไตล์ให้กับปุ่ม Python tkinter