How to have an background image and buttons on it in tkinter?

筅森魡賤 提交于 2021-01-24 11:29:50

问题


I'm writing a simple Python 3 program using tkinter. it should display a background picture and a button.

Here is the code:

import tkinter
from PIL import Image
from PIL import ImageTk

window = tkinter.Tk()
file = Image.open('/Users/dariushmazlumi/Desktop/p.jpg')
img = ImageTk.PhotoImage(file)
background = tkinter.Label(window, image=img)
background.image = img
background.pack()
window.minsize(height=window.winfo_height(), width=window.winfo_width())
number = 0
def buttonclicked():
    global number
    number = number+1
    button.configure(text=number)
button = tkinter.Button(window, text=0, command=buttonclicked)
button.grid(column=1, row=1)
window.mainloop()

Prior to this, I tried using button.pack(), but it shows button under the image, not on it(maybe the image is not background).

Next, I tried using button.grid(). It runs on the terminal with no error, but no visible output! It just runs. I don't know why.

I want my program to display an image and buttons on it (like a desktop for example).


回答1:


I found a simple way to do what you want which is much less complex that what I was suggesting in my comments. The essential steps are: Create a tkinter.Canvas, display the image on it with Canvas.create_image(), next create a Canvas.create_window() and finally put the tkinter.Button in that. Note that each Canvas "window" can only hold one widget, so you'll have to repeat the last two steps if you want to put more than one button on the image.

It may be simpler to understand by checking out the code below:

import tkinter as tk
from PIL import ImageTk, Image

class CanvasButton:
    def __init__(self, canvas):
        self.canvas = canvas
        self.number = tk.IntVar()
        self.button = tk.Button(canvas, textvariable=self.number,
                                command=self.buttonclicked)
        self.id = canvas.create_window(50, 100, width=25, height=25,
                                       window=self.button)
    def buttonclicked(self):
        self.number.set(self.number.get()+1)  # auto updates Button

root = tk.Tk()
root.resizable(width=False, height=False)
root.wm_attributes("-topmost", 1)

imgpath = 'archipelago_big.gif'
img = Image.open(imgpath)
photo = ImageTk.PhotoImage(img)

canvas = tk.Canvas(root, bd=0, highlightthickness=0)
canvas.pack()
canvas.create_image(0, 0, image=photo)

CanvasButton(canvas)  # create a clickable button on the canvas

root.mainloop()

Here's what it looks like after clicking on the button a few times:



来源:https://stackoverflow.com/questions/45843706/how-to-have-an-background-image-and-buttons-on-it-in-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!