Tkinter Button Background Image
Yes, we can set real image as background for a button. This time we are using but_2_img that will point to bg-img.gif.
Please note image extension, it must be .gif format:
but_2_img = PhotoImage(file = "bg-img.gif")
After .gif image is ready and set, we can connect it to button but_2. It's important to have command compound="c":
but_2 = Button(top_win, text="Calc", image = but_2_img, width = 100, height = 100,
fg = "white", font = ("Arial", 16), compound = "c", command = run_calc)
You are highly advised to watch corresponding YT tutorial that covers this topic.
Other things you know from previous tutorials, so this is our full working script:
from tkinter import *
import tkinter.messagebox as mb
import os
top_win = Tk()
top_win.geometry("500x500")
def run_calc():
os.system("calc")
but_2_img = PhotoImage(file = "bg-img.gif")
but_2 = Button(top_win, text="Calc", image = but_2_img, width = 100, height = 100,
fg = "white", font = ("Arial", 16), compound = "c", command = run_calc)
but_2.place(x = 0, y = 0)
top_win.mainloop()
Tkinter Button Packing
If you don't like messing around with pixels for placing buttons somewhere on app windows, we can use pack() method.
In that case horizontally we can use values LEFT, RIGHT, TOP, BOTTOM. Do not use quotes around those uppercase values.
Also, we will anchor buttons using values like "N", "NE", "E", "SE", "S", "SW", "W", "NW", and also "CENTER". Anchor values are points of the compass:
but_3 = Button(top_win, text="Notepad", command = run_notepad)
but_3.pack(side = LEFT, anchor = NW)
but_4 = Button(top_win, text="Notepad", command = run_notepad)
but_4.pack(side = LEFT, anchor = NW)
Full script:
from tkinter import *
import tkinter.messagebox as mb
import os
top_win = Tk()
top_win.geometry("500x500")
def run_notepad():
os.system("notepad")
but_3 = Button(top_win, text="Notepad", command = run_notepad)
but_3.pack(side = LEFT, anchor = NW)
but_4 = Button(top_win, text="Notepad", command = run_notepad)
but_4.pack(side = LEFT, anchor = NW)
top_win.mainloop()
Tkinter Button Relief
It's easy to set Relief for buttons. Just use relief uppercase values, without quotes: RAISED, FLAT, SUNKEN, GROOVE or RIDGE:
from tkinter import *
import tkinter.messagebox as mb
import os
top_win = Tk()
top_win.geometry("500x500")
def run_notepad():
os.system("notepad")
but_3 = Button(top_win, text="Notepad", relief = FLAT, command = run_notepad)
but_3.pack(side = LEFT, anchor = NW)
but_4 = Button(top_win, text="Notepad", relief = SUNKEN, command = run_notepad)
but_4.pack(side = LEFT, anchor = NW)
top_win.mainloop()
No comments:
Post a Comment