简体   繁体   中英

how to set background image to a window using Tkinter python 2.7

I was working on setting the background image and upon that image adding the labels, buttons and all. everything is coming, but not on the background image, its like this:

在此处输入图片说明

And my code is:

from Tkinter import Tk, Frame, BOTH
import Tkinter
from PIL import Image, ImageTk

class Example(Frame):

   def __init__(self, parent):
      Frame.__init__(self, parent)            
      self.parent = parent        
      self.initUI()

   def initUI(self):

      self.parent.title("PISE")
      self.pack(fill=BOTH, expand=1)

root = Tk()
root.geometry("1111x675+300+300")
app = Example(root)

im = Image.open('wood.png')
tkimage = ImageTk.PhotoImage(im)
Tkinter.Label(root,image = tkimage).pack()

custName = StringVar(None)
yourName = Entry(app, textvariable=custName)
yourName.pack()

relStatus = StringVar()
relStatus.set(None)

labelText = StringVar()
labelText.set('Accuracy Level')
label1 = Label(app, textvariable=labelText, height=2)
label1.pack()

radio1 = Radiobutton(app, text='100%', value='1', variable = relStatus, command=beenClicked1).pack()
radio2 = Radiobutton(app, text='50%', value='5', variable = relStatus, command=beenClicked5).pack()

root.mainloop()  

How to fit the background image properly?

Thanks in advance!

You should use place() for placing the image & then use grid() (personally i prefer grid) or pack() for other widgets.

from Tkinter import Tk, Frame, BOTH
import Tkinter
from PIL import Image, ImageTk

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)            
        self.parent = parent        
        self.initUI()

    def initUI(self):
        self.parent.title("PISE")
        self.pack(fill=BOTH, expand=1)

root = Tk()
root.geometry("1111x675+300+300")
app = Example(root)

im = Image.open('Test1.png')
tkimage = ImageTk.PhotoImage(im)
myvar=Tkinter.Label(root,image = tkimage)
myvar.place(x=0, y=0, relwidth=1, relheight=1)

custName = StringVar(None)
yourName = Entry(root, textvariable=custName)
yourName.pack()

relStatus = StringVar()
relStatus.set(None)

labelText = StringVar()
labelText.set('Accuracy Level')
label1 = Label(root, textvariable=labelText, height=2)
label1.pack()

def beenClicked1():
    pass

def beenClicked5():
    pass

radio1 = Radiobutton(root, text='100%', value='1', variable = relStatus, command=beenClicked1).pack()
radio2 = Radiobutton(root, text='50%', value='5', variable = relStatus, command=beenClicked5).pack()

root.mainloop()

The reason the widgets were not visible was because you were using two different parents ,ie, app (its an Instance of class Example ,so don't use this) and root .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM