im relatively new to coding and am trying to display an image on tkinter, i have it set so when you press on a button on the first screen it will open to another screen - i have got this working fine my issue is that when the new window is opened the image that should be on the second screen goes onto the first screen, and i cannot work out how to fix it. I dont get any errors it just puts the image in the middle of the first screen, I hope this makes sense. Thanks
The code is below: (for the second screen that should be displaying the image but isnt)
from tkinter import *
window2 = Tk()
window2.geometry("1920x1200")
Namearea = Label(window2, text = "Please Name the Prebuild: ")
Namearea.pack()
e = Entry(window2, width=50, borderwidth=3, bg="Light Grey", fg="black")
e.pack()
e.insert(0, "Remove this text and Enter the name of your prebuild: ")
# this is the part for the image
img3 = PhotoImage(file=r"C:\Tkinter\ComputerImage.png ")
picture1 = Label(image=img3)
picture1.pack()
SaveAndContinue = Button(window2, text = "Save and Return to Main Menu", padx = 75, pady = 20, bg = "Light Grey")
SaveAndContinue.pack()
LinkTitle = Label(window2, text = "Here are some links to purchase the parts from:")
Link1 = Label(window2, text = "Scorptec: www.scorptec.com.au/")
Link2 = Label(window2, text = "Centre-Com: www.centrecom.com.au/")
LinkTitle.pack()
Link1.pack()
Link2.pack()
Since you used multiple instances of Tk() (one for first window, one for second window), you need to specify the parent for picture1 and img3:
img3 = PhotoImage(master=window2, file=r"C:\Tkinter\ComputerImage.png")
picture1 = Label(window2, image=img3)
picture1.pack()
However, you should avoid using multiple instances of Tk(). Better change second instance of Tk() to Toplevel().
Hey you forgot to mention the window name in picture1 = Label(image=img3)
here is the right one the mistake
# this is the part for the image
img3 = PhotoImage(file=r"C:\\Tkinter\\ComputerImage.png ")
picture1 = Label(window2,image=img3)
picture1.pack()
And the
error error _tkinter.TclError: image "pyimage4" doesn't exist -
You have to use Toplevel() in second window
window2=Toplevel ()
It works for me
Related
I've been trying for about a week now but I can't seem to figure out what I did wrong. My button will not respond when I click it, and even after adding a command it would just display it when I run the program. If I put the disable command, I can see the button change to disabled. Please help if you can.
from tkinter import *
screen = Tk()
screen.title = ("My first")
screen.geometry("800x500")
#create a label
myLabel1 = Label(screen, text = "First Program")
myLabel2 = Label(screen, text = "Yeah Buddy")
#place onto screen using grid system
myLabel1.grid(row=0,column=0)
myLabel2.grid(row=1,column=1)
#Create a text box:
txtfield = Entry(screen, width=50, bg="blue", fg= "white")
txtfield.grid(row=2, column =2 )
#command for click (you need to have function appear before where you intend to use it for it to execute.)
def myClick():
myResponse = Label(screen, text= "Button clicked" + txtfield.get())
myResponse.grid(row=4, column=2)
#make a button
myButton = Button(screen, text="Test Button", command = myClick())
myButton.grid(row=3, column=2)
screen.mainloop()
You're calling myClick instead of passing the function itself as a parameter. command=myClick
I wanted to make my app look more beautiful and it's harder than I though! Now I had an app with mainly 2 buttons and date-time label on top. Buttons are just with text, but I want to use pictures on them. That's my code now:
def showMainMenu():
global cardNumber, allowToGPIO
cardNumber = "" #Reset cardNumber global value
allowToGPIO = True
clear()
showNewTime()
watchDog.awake()
GuestTestButton = Button(canvas, text="GUEST TEST", width=buttonwidth, height=buttonheight, compound = TKinter.CENTER, command = guestTest)
GuestTestButton.config(font=("Mojave-Regular.ttf", 24))
#GuestTestButton.pack()
GuestTestButton.place(x=90, y=100)
AddEmployeeButton = Button(canvas, text="ADD NEW USER", width=buttonwidth, height=buttonheight, compound = TKinter.CENTER, command = addEmployee)
AddEmployeeButton.config(font=("Mojave-Regular.ttf", 24))
#AddEmployeeButton.pack()
AddEmployeeButton.place(x=90, y=270)
And for now, it works. But when I tried to make them more colorful (just use image instead of text), button shows up without anything on it. Is it even possible to make things like that in TKinter? Everything I do is on canvas:
app = TKinter.Tk()
canvas = TKinter.Canvas()
I tried to do this that way:
GuestImage = TKinter.PhotoImage(file="guest.gif")
GuestTestButton = Button(canvas, text="GUEST TEST", width=buttonwidth, height=buttonheight, compound = TKinter.CENTER, command = guestTest)
GuestTestButton.config(image=GuestImage, font=("Mojave-Regular.ttf", 24))
GuestTestButton.place(x=90, y=100)
But as I said, it's not working properly :D Thanks in advance for any help!
I got it now, my images shows up but it dissapears after miliseconds, now I made the GuestImage and AddEmployeeImage as global variables and it works perfectly!
So I am trying to make a text-based game, but also want to incorporate images into it, I have a main menu, a window that is always open, and then a game window, that should have the image in, but for some reason, it appears in the menu window instead. Has anyone got any idea why?
def menu():
master = Tk()
master.geometry("350x300")
master.wm_iconbitmap("zombie.ico")
master.configure(background = '#484a2c')
master.title("Menu")
def game():
master = Tk()
master.geometry("800x500")
master.title("Game")
master.wm_iconbitmap("zombie.ico")
master.configure(background = '#484a2c')
image = PhotoImage(file="Kitchenimage.gif")
label5 = Label(image=image)
label5.image = image
label5.pack()
label = Label(master, text = "Zombie Mansion", background = '#484a2c',
font = ("AR CHRISTY", 30))
label.pack()
b = Button(master,text = "Play Game", height = 1, width = 10)
b.config(background = '#484a2c', activebackground = '#484a2c', font =
("AR CHRISTY", 14), command = get_username)
b.place(x = 120, y = 70)
mainloop()
"Why is my image appearing on the wrong window in Tkinter?"
Assuming you have another instance of Tk as what you refer to as main menu somewhere in your code that you're not showing us like:
main = Tk()
in addition to master = Tk() in your game method, then it's because when you instantiate widgets without passing a parent widget explicitly like in:
label5 = Label(image=image)
then the widget's parent defaults to the Tk instance whose mainloop is being run, in above case supposedly main's. By default widgets are shown under their parents, hence the reason.
Pass parent explicitly like:
label5 = Label(master=main, image=image)
or
label5 = Label(master, image=image)
In most cases, if not all cases, you shouldn't have multiple instances of Tk. If you require additional windows, please use Toplevel widget.
I'm trying to open a second window (defined by the function 'learn') from the main program - the window opens with no problem but the buttons/images don't show up. Does anyone know what I'm doing wrong? All the images are .gif files and sit in the same folder as the program.
I wrote the code under 'learn' in a separate python file. Initially I had tried to open that file as a separate program but it didn't work.
from tkinter import *
import linecache
import os
root = Tk()
root.geometry('1200x800') #Dimensions of the window
root.title("stud(y)ious") #title of the window
container1 = Frame(root)
container1.pack(side = TOP, anchor = W)
container2= Frame(root) #Bottom container
container2.pack(side = BOTTOM,pady = 50) #space between the bottom of the timetable and the two buttons; initially this was cropping the timetable too much so this value was DECREASED in order to shorten the amount of padding that exists around the two buttons at the bottom
#All the images used on the home page; keeping them all in one place so they can be eaisly replaced by anotehr programmer if need be
imgNote = PhotoImage(file='img_note.gif') #'N O T E'
imgHeader = PhotoImage(file='img_title.gif') #'stud(y)ious' 'T I M E T A B L E'
imgTimetable = PhotoImage(file='btn_timetable.gif') #replacable timetable image
imgCreateBtn = PhotoImage(file='btn_create.gif') #'create'
imgLearnBtn = PhotoImage(file='btn_learn.gif') #'learn'
toolbar = Canvas()
Header = Label(toolbar, image = imgHeader).pack() #creation of header, space for imgHeader; above and seperated from main buttons
toolbar.pack()
def destroy(): #closing the window
root.destroy()
def create(): #The window that appears when the 'create' button is clicked
toplevel = Toplevel()
labelCreateHeader = Label(toplevel, image=imgNote) #header graphic
labelCreateHeader.pack()
labelCreateText = Label(toplevel, text=txtCreate) #text (from variable noted below)
labelCreateText.pack()
def learn(): #The window that appears when the 'learn' button is clicked
window1 = Tk()
window1.geometry('1200x800')
window1.title("stud(y)ious: Learn") #title of the window, colon to show connection to studyious_main.py
#Opens the questions file (in read mode) and makes a list of them, one per line
with open('studyious_questions.txt', 'r+') as questionfile:
questions = questionfile.readlines()
#Takes off the '\n' from the end of each line so they are neatly presented and easy to read
questions = [i.strip('\n') for i in questions]
#reading answers; holds a string only - default value ""; type checking
ans1 = StringVar()
ans2 = StringVar()
ans3 = StringVar()
ans4 = StringVar()
ans5 = StringVar()
answers = []
for i in range(1,9):
answers.append(linecache.getline('studyious_answers.txt', i))
answers = [i.strip('\n') for i in answers]
def destroy2():
window1.destroy() #closes window, function attached to '⬅' button
def answering(answer, index): #The window that appears when the 'create' button is clicked
toplevel = Toplevel()
labelCorrectHeader = Label(toplevel, text=txtInfoCorrect, image=imgCorrect) #header graphic
labelCorrect = Label(toplevel, text=txtInfoCorrect) #text (from variable noted below)
labelIncorrectHeader = Label(toplevel, text=txtInfoIncorrect, image=imgIncorrect)
labelIncorrect = Label(toplevel, text=txtInfoIncorrect)
if answer == answers[index]: #selection structure to decide whether the 'correct' (if) or 'incorrect' (else) window pops up
labelCorrectHeader.pack()
labelCorrect.pack()
else:
labelIncorrectHeader.pack()
labelIncorrect.pack()
#The following two text variable were written using triple quotations so the program would register line breaks effectively
txtInfoCorrect = """
Keep up the good work!
Remember, for every 10 questions, take a lil' break <3
"""
txtInfoIncorrect = """
Better luck next time!
Keep going, you can do it!
"""
container01 = Frame(window1)
container01.pack(anchor = W)
ButtonQuit = Button(container01, command=destroy2) #FIXME should open the other python file, containing the homepage
ButtonQuit["text"] = "⬅"
ButtonQuit.pack(side = LEFT, padx = 10, pady = 8)
#Directory of images used in this program
imgCorrect = PhotoImage(file='img_correct.gif')
imgIncorrect = PhotoImage(file='img_incorrect.gif')
imgAnswer = PhotoImage(file='btn_answer.gif')
imgHeaderb = PhotoImage(file='img_header.gif')
toolbar1 = Canvas()
Header1 = Label(toolbar1, image = imgHeaderb).pack() #Placing the header image (img_header) at the top of the page
toolbar1.pack()
#THE QUESTIONS
question1 = Label(window1, text=questions[0]).pack(pady = 10) #states the question according to it's number in the list (e.g this one is 0 because it is the first item in the studyious_questions.txt file
#pady refers to the space between each of teh questions (so things dont look too cluttered and unprofessional)
entry1= Entry(window1, textvariable = ans1) #User can cnter answer to to entry box
entry1.pack()
ButtonAnswer1 = Button(image = imgAnswer,command=lambda:answering(ans1.get(), 0)).pack() #answer button, when clicked entered answer will be checked against teh answer recorded in studyious_answers.txt to see if it is correct
#For example, for the example above, the answer entered by the user is checked against the first answer in the list of answers (index of 0) to see if it correct; promopting a response from the variable 'answering' (which will either produce the 'correct' or 'incorrect dialogue window)
question2 = Label(window1, text=questions[1]).pack(pady = 10)
entry2= Entry(window1, textvariable = ans2)
entry2.pack()
ButtonAnswer2 = Button(image = imgAnswer,command=lambda:answering(ans2.get(), 1)).pack()
question3 = Label(window1, text=questions[2]).pack(pady = 10)
entry3= Entry(window1, textvariable = ans3)
entry3.pack()
ButtonAnswer3 = Button(image = imgAnswer,command=lambda:answering(ans3.get(), 2)).pack()
question4 = Label(window1, text=questions[3]).pack(pady = 10)
entry4= Entry(window1, textvariable = ans4)
entry4.pack()
ButtonAnswer4 = Button(image = imgAnswer,command=lambda:answering(ans4.get(), 3)).pack()
question5 = Label(window1, text=questions[4]).pack(pady = 10)
entry5= Entry(window1, textvariable = ans5)
entry5.pack()
ButtonAnswer5 = Button(image = imgAnswer,command=lambda:answering(ans5.get(), 4)).pack()
window1.mainloop()
txtInfo = """
text
"""
txtCreate = """
text
"""
def timetable():
toplevel = Toplevel() #Ensure window pops up above the main window as a pop up window
labelTimetableHeader = Label(toplevel, image=imgNote) #header graphic to match aesthetic of the rest of the program
labelTimetableHeader.pack()
labelTimetableText = Label(toplevel, text=txtInfo) #The main body of text (as seen above in txtInfo)
labelTimetableText.pack()
btnQuit = Button(container1,command=destroy) #Quit button, closes window
btnQuit["text"] = "Quit"
btnQuit.pack(side = LEFT, padx = 10, pady = 8) #the difference between the top and left padding is that there is automatically two points of padding from the top of the window
TimetableButton = Button(image = imgTimetable,command=timetable).pack() #a replacable image that allows users to enter place their own timetable on the home page
#Initially the button sat squished in the corner whih made the finishing of the home page look very rough, cluttered and unprofessional
#Button 1; opens a small window giving the user details of how to enter the questions and answers they wish to test themselves on
btnCreate = Button(container2, image = imgCreateBtn,command=create).pack(side = LEFT, padx =100) #padding around teh sides seperates the two buttons - 'create' and 'learn'
#Button 2; redirect to the quiz program, opening another window with the quiz program
btnLearn = Button(container2, image = imgLearnBtn,command=learn).pack(side = BOTTOM, padx = 100)
root.mainloop()
You forgot to put window1 as the master of any of your buttons like this one:
ButtonAnswer1 = Button(image = imgAnswer,command=lambda:answering(ans1.get(), 0)).pack()
add window1 to all your ButtonAnswer1-5:
ButtonAnswer1 = Button(window1, image = imgAnswer,command=lambda:answering(ans1.get(), 0)).pack()
First time coding in Python with tkinter; online searches and the manual have not worked (for me).
Below is an example of the issue:
(I would put an image, but I'm sub 10 reputation so I cannot).
I have a definition that loads the other parts of the system named Load_Main_Menu. You can access the food menu, drink menu, etc from here. For ease of use I have edited it so that you don't have to write out code to get it to work.
I have a definition that displays the main menu, buttons the user can use to get into other parts of the system. I've reduced the code I already have so you can copy and paste it and see what I mean:
import tkinter#Imports Tkinter. Used for the user interface.
from tkinter import *#Imports the package tkinter for the user interface.
from tkinter import ttk#Imports the ttk module, used in the Food/Drink menus.
root = Tk()
tree = ttk.Treeview(root)
def Load_Main_Menu():#Loads the main menu (Food, Drink, Exit, etc.)
#Positions the buttons by setting topFrame as the top (re:First), bottomFrame as
#bottom (re: Last) and then the other buttons fill the space between
Top_Frame = Frame(root)
Top_Frame.pack()
Bottom_Frame = Frame(root)
Bottom_Frame.pack(side = BOTTOM)
#This chunk of code creates the buttons, sets the text, links it to the
#function and also decides it's colour.
Menu_Food_Button = Button(Top_Frame, text = "Food", command = Food_Button, fg = 'Blue')
Menu_Stock_Button = Button(Top_Frame, text = "Stock Control", command = Stock_Control_Button, fg = 'Green')
#The code below determines which side of the parent widget packs against.
Menu_Food_Button.pack(side=LEFT)
Menu_Stock_Button.pack(side=LEFT)
root.mainloop()
def Food_Menu():
tree['columns'] = ('Price', 'Qty', 'Print Receipt')#additional columns after the default '#0'
tree.column('Price', stretch = 0, width = 100, anchor = E)#Price Column, tkinter.E aligns contents to the "east"
tree.column('Qty', stretch = 0, width = 100, anchor = E)#Quantity Column
tree.column('Print Receipt', stretch = 0, width = 100, anchor = E)#Print Receipt Column
tree.heading('#0', text = "Item")# default column responsible for tree mechanics
tree.heading('Price', text = "£")
tree.heading('Qty', text = "Quantity")
tree.heading('Print Receipt', text = "Get Receipt")
tree.insert('', 0, 'Print_Receipt', text = "Get Receipt")#
tree.insert('', 0, '_Chips_', text = "Chips", values = (4.99, 133))#Parent, text goes to '#0', values go to tree['columns']
tree.insert('_Chips_', 0, text = "Add to Order")#Child
tree.pack()
root.mainloop()
def Stock_Menu():#Loads the main menu (Food, Drink, Exit, etc.)
#Positions the buttons by setting topFrame as the top (re:First), bottomFrame as
#bottom (re: Last) and then the other buttons fill the space between
Top_Frame = Frame(root)
Top_Frame.pack()
Bottom_Frame = Frame(root)
Bottom_Frame.pack(side = BOTTOM)
#This chunk of code creates the buttons, sets the text, links it to the
#function and also decides it's colour.
Stock_Exit_Button = Button(Top_Frame, text = "Exit", command = Return_To_Main_Menu, fg = 'Green')
#The code below determines which side of the parent widget packs against.
Stock_Exit_Button.pack(side=LEFT)
root.mainloop()
def Food_Button():#This displays the food menu.
Food_Menu()
def Stock_Control_Button():#This displays the stock options
Stock_Menu()
def Return_To_Main_Menu():#Loads the main menu
Load_Main_Menu()
Load_Main_Menu()
So, if you've C&P that you'll see a window come up with two buttons, Food and Stock.
Click Food,
Click Stock,
Click Exit,
Click Stock,
Click Exit.
You should see the issue. I want to be able to close the window 'behind me' so they don't pile up because it's a bug that kind of needs to be fixed, but I don't know how.
I've looked online, as I've said, and come up with nothing.
I fixed the indentation and root.mainloop() suggestions by the other answers. If you don't need the tree to be shown anymore, you could use tree.destroy(). However, I think it's more appropriate to use tree.pack_forget() in this case as suggested by this answer here.
I added the tree.pack_forget() to your Return_To_Main_Menu() function and removed the original Load_Main_Menu() call since it would create two new Food and Stock buttons.. I removed the comments from the original post just for easier posting.
import tkinter
from tkinter import *
from tkinter import ttk
root = Tk()
tree = ttk.Treeview(root)
def Load_Main_Menu():
Top_Frame = Frame(root)
Top_Frame.pack()
Bottom_Frame = Frame(root)
Bottom_Frame.pack(side = BOTTOM)
Menu_Food_Button = Button(Top_Frame, text = "Food", command = Food_Button, fg = 'Blue')
Menu_Stock_Button = Button(Top_Frame, text = "Stock Control", command = Stock_Control_Button, fg = 'Green')
Menu_Food_Button.pack(side=LEFT)
Menu_Stock_Button.pack(side=LEFT)
root.mainloop()
def Food_Menu():
tree['columns'] = ('Price', 'Qty', 'Print Receipt')
tree.column('Price', stretch = 0, width = 100, anchor = E)
tree.column('Qty', stretch = 0, width = 100, anchor = E)
tree.column('Print Receipt', stretch = 0, width = 100, anchor = E)
tree.heading('#0', text = "Item")
tree.heading('Price', text = "£")
tree.heading('Qty', text = "Quantity")
tree.heading('Print Receipt', text = "Get Receipt")
tree.insert('', 0, 'Print_Receipt', text = "Get Receipt")
tree.insert('', 0, '_Chips_', text = "Chips", values = (4.99, 133))
tree.insert('_Chips_', 0, text = "Add to Order")#Child
tree.pack()
def Stock_Menu():
Top_Frame = Frame(root)
Top_Frame.pack()
Bottom_Frame = Frame(root)
Bottom_Frame.pack(side = BOTTOM)
Stock_Exit_Button = Button(Top_Frame, text = "Exit", command = Return_To_Main_Menu, fg = 'Green')
Stock_Exit_Button.pack(side=LEFT)
def Food_Button():
Food_Menu()
def Stock_Control_Button():
Stock_Menu()
def Return_To_Main_Menu():
tree.pack_forget()
Load_Main_Menu()