This question already has answers here:
Image on a button
(5 answers)
Closed 8 years ago.
When I try to add and image to the button, the program will run, but the button will be blank and you cannot click on it. If I change image=Tkinter.PhotoImage(file="C:/TeDOC/OpenFolder.gif") to text='Open Directory it works fine and you are able to click the button. I have no idea why when I change it to an img, it does not work. Any help will be appreciated.
Here is my code:
import Tkinter, Tkconstants, tkFileDialog
class TkFileDialogExample(Tkinter.Frame):
def __init__(self, root):
Tkinter.Frame.__init__(self, root)
# options for buttons
button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}
# define buttons
Tkinter.Button(self, image=Tkinter.PhotoImage(file="C:/TeDOC/OpenFolder.gif"), command=self.askdirectory).pack(**button_opt)
# defining options for opening a directory
self.dir_opt = options = {}
options['initialdir'] = 'C:\\'
options['mustexist'] = False
options['parent'] = root
options['title'] = 'This is a title'
def askdirectory(self):
#Returns a selected directoryname.
return tkFileDialog.askdirectory(**self.dir_opt)
if __name__=='__main__':
root = Tkinter.Tk()
TkFileDialogExample(root).pack()
root.mainloop()
First you have to define your image, using the self.image. So try:
self.image = Tkinter.PhotoImage(file="C:/TeDOC/OpenFolder.gif")
Then under your button, put:
Tkinter.Button(self, image=self.image, command=self.askdirectory).pack(**button_opt)
You must save the image in self.
self.image = Tkinter.PhotoImage(file="C:/TeDOC/OpenFolder.gif")
Tkinter.Button(..., image=Tkinter.PhotoImage(file="C:/TeDOC/OpenFolder.gif"), ...
If it is deleted it will not be displayed.
Related
This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 10 months ago.
I was trying to show the image when I clicked the button however it failed( the program does not report an error but the image is still not displayed). I'm sure I put the right path to the picture. This is code
import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk()
def def_btn1():
image1 = Image.open("csdl.png")
image1 = image1.resize((710, 400), Image.ANTIALIAS)
test = ImageTk.PhotoImage(image1)
lbl2 = tk.Label(image=test)
lbl2.pack()
btn1 = tk.Button(text="click to show", relief=tk.RIDGE, width=15, font=(12),command=def_btn1)
btn1.pack()
window = tk.mainloop()
I want when I click the button the image will show in the program. Thank you!
You need to add lbl2.image = test for the image to not be destroyed by tkinter, you new code should be this -
import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk() # You might want to move this line below your functions, with the other global variables
def def_btn1():
image1 = Image.open("csdl.png")
image1 = image1.resize((710, 400), Image.ANTIALIAS)
test = ImageTk.PhotoImage(image1)
lbl2 = tk.Label(image=test)
lbl2.image = test # You need to have this line for it to work, otherwise it is getting rid of the image. the varibale after the '=' must be the same as the one calling "ImageTk.PhotoImage"
lbl2.pack()
btn1 = tk.Button(text="click to show", relief=tk.RIDGE, width=15, font=(12),command= lambda : def_btn1()) # adding 'lambda :' stops the function from running straight away, it will only run if the button is pressed
btn1.pack()
window = tk.mainloop()
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 1 year ago.
I'm working on a custom button for a list, and want to make it change color when the mouse hovers above the button. See the following code for how I'm trying to do it:
import tkinter as tk
from tkinter import *
class list_button:
def __init__(self, container, text, font_size):
self.list_button = tk.Button(container, text=text, font = ("helvatica", (0 + font_size)), relief = "flat")
self.list_button.pack()
self.list_button.bind('<Enter>', self.enter_func(self))
self.list_button.bind('<Leave>', self.leave_func(self))
def enter_func(self, key):
print("Enter")
self.list_button.configure(bg = "grey")
def leave_func(self, key):
print("Leave")
self.list_button.configure(bg = "white")
root = tk.Tk()
for i in range(10):
list_button(root, i, 15)
root.mainloop()
What seems to happen is that the code calls the function once and then unbinds the function.
What am I doing wrong here?
For people that are stuck on the same problem. This is the revised code:
import tkinter as tk
from tkinter import *
class list_button:
def __init__(self, container, text, font_size):
self.list_button = tk.Button(container, text=text, font = ("helvatica", (0 + font_size)), relief = "flat")
self.list_button.pack()
self.list_button.bind('<Enter>', self.enter_func)
self.list_button.bind('<Leave>', self.leave_func)
def enter_func(self, key):
print("Enter")
self.list_button.configure(bg = "grey")
def leave_func(self, key):
print("Leave")
self.list_button.configure(bg = "white")
root = tk.Tk()
for i in range(10):
list_button(root, i, 15)
root.mainloop()
The changes are in the following part:
self.list_button.bind('<Enter>', self.enter_func)
self.list_button.bind('<Leave>', self.leave_func)
This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 2 years ago.
So, I am trying to build an MP3-player. I have got my project structured like this:
source
main.py
content
controls.py
gui.py
Here is the code from those modules:
main.py
from tkinter import *
from source.content import gui
def main():
# Defining our root window
root = Tk()
root.title("MMP3 - Mini MP3 Player")
root.geometry("480x640")
root.resizable(False, False)
root.config(bg="#2B2B2B")
gui.Gui(root)
root.mainloop()
main()
gui.py
from source.content import controls
class Gui:
def __init__(self, master):
controls.Controls(master)
controls.py
from tkinter import *
class Controls:
def __init__(self, master):
self.controlsFrame = Frame(master)
self.controlsFrame.grid(row=0, column=0)
self.play_controls()
def play_controls(self):
# Getting button images
self.img_prev = PhotoImage(file="E:/PyCharm Projects/Images/icons/previous.png")
self.img_stop = PhotoImage(file="E:/PyCharm Projects/Images/icons/stop.png")
self.img_play = PhotoImage(file="E:/PyCharm Projects/Images/icons/play.png")
self.img_pause = PhotoImage(file="E:/PyCharm Projects/Images/icons/pause.png")
self.img_next = PhotoImage(file="E:/PyCharm Projects/Images/icons/next.png")
# Placing buttons
self.btn_prev = Button(self.controlsFrame, image=self.img_prev, activebackground="#2B2B2B",
borderwidth=1)
self.btn_prev.grid(row=0, column=0, ipadx="5px")
self.btn_stop = Button(self.controlsFrame, image=self.img_stop, activebackground="#2B2B2B",
borderwidth=1)
self.btn_stop.grid(row=0, column=1, ipadx="5px")
self.btn_play = Button(self.controlsFrame, image=self.img_play, activebackground="#2B2B2B",
borderwidth=1)
self.btn_play.grid(row=0, column=2, ipadx="5px")
self.btn_pause = Button(self.controlsFrame, image=self.img_pause, activebackground="#2B2B2B",
borderwidth=1)
self.btn_pause.grid(row=0, column=3, ipadx="5px")
self.btn_next = Button(self.controlsFrame, image=self.img_next, activebackground="#2B2B2B",
borderwidth=1)
self.btn_next.grid(row=0, column=4, ipadx="5px")
The problem is, when I try to create and place my buttons onto the screen, they take up space, but they are not clickable and contain no image. However, if I add text to them instead of images, everything works completely fine.
Also, if I run the code for images, button creation and placing from controls.py just in main, (as if there was no Controls class) then everything is good as well.
I suspect that you are losing the reference to the images. In order to keep them you need to store the controls class as a variable inside your GUI class. Try this;
class Gui:
def __init__(self, master):
self.controls = controls.Controls(master)
I'm a beginner trying to use tkinter to create a GUI. I've adapted code from other sources for my own use.
At the moment I'm trying to display an image along with a button.
However, when running the code, only the image displays no matter where I move the button, the button isn't displayed.
Would be grateful for any help.
Additional functionality:
I'm looking to implement a function so that I can move the image around using coordinates, also a function that allows me to use .jpg instead of .png.
Thanks in advance!
Code:
from tkinter import *
from PIL import Image, ImageTk
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("WindowName")
self.pack(fill = BOTH, expand = 1)
quitButton = Button(self, text = "quit", command=self.client_exit)
quitButton.place(x=400,y=400)
self.showImg()
def client_exit(self):
exit() # Or another function
def showImg(self):
self.grid(row=0)
self.columnconfigure(0,weight=1)
self.rowconfigure(0,weight=1)
self.original = Image.open('wire.png')
resized = self.original.resize((200, 200),Image.ANTIALIAS)
self.image = ImageTk.PhotoImage(resized)
self.display = Label(self, image = self.image)
self.display.grid(row=0)
root = Tk()
root.geometry("600x600")
app = Window(root)
root.mainloop()
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 5 years ago.
I'm trying to create a sticky-note program in Python to practice. I want to create a button such that when clicked, the background of the text box changes to yellow. My code is below:
from tkinter import *
import random
color = ['burlywood2', 'seagreen1', 'steelblue1', 'gold']
randomColor = random.choice(color)
class Sticky(Frame):
def __init__(self, master):
Frame.__init__(self, master)
master.minsize(width=250, height=200)
master.configure(background=randomColor)
self.pack(fill=BOTH, expand=YES)
self.txtEntry = Text(background=randomColor, highlightthickness=0, relief=RAISED)
self.txtEntry.pack(fill=BOTH, expand=YES)
myString = input("Enter your text here: ")
self.txtEntry.insert(END, myString)
self.createWidgets()
def createWidgets(self):
self.QUIT = Button(self)
self.QUIT["text"] = "Completed"
self.QUIT["fg"] = "white"
self.QUIT["background"] = "green"
self.QUIT["command"] = self.quit
self.QUIT.pack(fill=BOTH, expand=YES)
self.URGENT = Button(self)
self.URGENT["text"] = "URGENT"
self.URGENT["fg"] = "yellow"
self.URGENT["background"] = "red"
self.URGENT["command"] = self.highLight()
self.URGENT.pack(fill=BOTH, expand=YES)
def highLight(txtEntry):
txtEntry.configure(background='yellow')
txtEntry.update()
I can't seem to get it to work. When the "URGENT" button is clicked, nothing happens. Thanks for any advice
highLight is an instance method*, so its first argument should be self, not txtEntry. Even without passing it as an argument, you can still access txtEntry as an attribute of self rather than as a local name.
def highLight(self):
self.txtEntry.configure(background='yellow')
When you do self.URGENT["command"] = self.highLight, you are telling Python "call self.highLight() right now, then take the return value of that function and assign it to the command property". But highLight returns None, so the button ends up with no command at all. Perform the assignment without the parentheses so that self.highLight is assigned to the property instead of its return value.
self.URGENT["command"] = self.highLight
(*at least, I assume it is. Your indentation is screwed up so it's not clear which of your defs are actually inside the Sticky class definition.)