I've been trying to add an image so that my buttons sit on top of the image, but have only been able to make the image cover everything completely or force the image to be underneath the horizontal part the buttons cover.
Here is the relevant code for it:
class MainMenu(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.master = master
self.initUI()
def initUI(self):
self.master.title("Adventure")
bg = PhotoImage(file="Background-gif.gif")
newGameButton = Button(self, text="New Game", height=2, width=20, command=self.newGame)
newGameButton.pack(side=TOP, pady=50)
loadGameButton = Button(self, text="Load Game", height=2, width=20, command=self.loadGame)
loadGameButton.pack(side=TOP)
quitButton = Button(self, text="Quit", height=2, width=20, command=self.close)
quitButton.pack(side=TOP, pady=50)
label = Label(self, image=bg)
label.image = bg
label.pack(fill=BOTH, expand=1)
self.pack()
Many thanks.
You could place an image on a canvas, and then place a button on the canvas:
import Tkinter as tk
import ImageTk
FILENAME = 'image.png'
root = tk.Tk()
canvas = tk.Canvas(root, width=250, height=250)
canvas.pack()
tk_img = ImageTk.PhotoImage(file = FILENAME)
canvas.create_image(125, 125, image=tk_img)
quit_button = tk.Button(root, text = "Quit", command = root.quit, anchor = 'w',
width = 10, activebackground = "#33B5E5")
quit_button_window = canvas.create_window(10, 10, anchor='nw', window=quit_button)
root.mainloop()
Related
I currently have a function that shows a new screen (lets call it A), then does a countdown of 10 seconds. After the 10 seconds, it takes the user to a new screen (B). I would like to make the .after command not execute if the user clicks a button on screen 'A' before the 10 seconds.
class MainGate3(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
background_image = tk.PhotoImage(file="Sylvanas.png") # Displays whats in the file
background_label = tk.Label(self, image=background_image) # Makes tk.Label display the background_image
background_label.place(x=0, y=0, relwidth=1, relheight=1) # Adjusts the height/width
background_label.image = background_image # Recognises the label as an image
def gate():
controller.show_frame("MainGate4")
button1.after(10000, lambda:controller.show_frame("MainMenu"))
button1 = tk.Button(self, text="Commence Battle", bg="black", fg="white", height=2, width=20,
command=gate)
button1.place(x="712", y="433")
class MainGate4(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
background_image = tk.PhotoImage(file="Sylvanas1.png") # Displays whats in the file
background_label = tk.Label(self, image=background_image) # Makes tk.Label display the background_image
background_label.place(x=0, y=0, relwidth=1, relheight=1) # Adjusts the height/width
background_label.image = background_image # Recognises the label as an image
button1 = tk.Button(self, text="Parry Right", bg="black", fg="white", height=2, width=20,
command=lambda: controller.show_frame("MainGate3"))
button2 = tk.Button(self, text="Parry Left", bg="black", fg="white", height=2, width=20,
command=lambda: controller.show_frame("MainGate3"))
button3 = tk.Button(self, text="Dodge", bg="black", fg="white", height=2, width=20,
command=lambda: controller.show_frame("MainGate3"))
button1.place(x="83", y="140")
button2.place(x="83", y="240")
button3.place(x="83", y="340")
The after method returns an identifier. You can use the identifier to cancel by after_cancel method later.
import tkinter as tk
class GUI(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.action = None
tk.Button(self,text="Print in 10 sec",command=self.callback).pack()
tk.Button(self, text="Cancel print", command=self.cancel_callback).pack()
def callback(self):
self.action = self.after(10000,lambda: print ("Hi"))
def cancel_callback(self):
if self.action:
self.after_cancel(self.action)
print ("Print cancelled")
root = GUI()
root.mainloop()
I am trying to draw a image on a canvas in my tkinter gui. But when I draw text it is displayed I was wondering why it does not display and how I can fix it?
import tkMessageBox, PIL.ImageTk, PIL.Image, socket, queue, ttk
from threading import Thread
from Tkinter import *
class GUI(Frame):
def __init__(self, parent):
Frame.__init__(self,parent)
self.pack()
def main(self):
self.bBar = Frame(self, bg="#3A3A3C", bd=0)
self.bBar.place(x=0, y=450, width=700, height=600)
self.can = Canvas(self.bBar, width=700, height=50, highlightthickness=0, bg="red", bd=0)
img = PIL.ImageTk.PhotoImage(PIL.Image.open("Images/uBar.png"))
self.can.pack()
self.can.create_text(100, 10, text="My Text")
self.can.create_image(10,10, image=img, anchor=NW)
if "__Main__":
root = Tk()
root.title("Frozen Cloud")
root.geometry("700x500")
root.config(background="White")
root.resizable(0,0)
root.iconbitmap("Images/Icon.ico")
gui = GUI(root)
#gui.splashSc()
gui.mScreen()
root.mainloop()
Try this, you have used self but not defined within a function, also root = tk() should be at the start.
root = Tk()
def main(self):
self.bBar = Frame(self, bg="#3A3A3C", bd=0)
self.bBar.place(x=0, y=450, width=700, height=600)
self.can = Canvas(self.bBar, width=700, height=50, highlightthickness=0, bg="red", bd=0)
img = PIL.ImageTk.PhotoImage(PIL.Image.open("Images/uBar.png"))
self.can.pack()
self.can.create_text(100, 10, text="My Text")
self.can.create_image(10,10, image=img, anchor=NW)
if "__Main__":
root.title("Frozen Cloud")
root.geometry("700x500")
root.config(background="White")
root.resizable(0,0)
root.iconbitmap("iImages/Icon.co")
gui = GUI(root)
#gui.splashSc()
gui.mScreen()
root.mainloop()
I have been looking at my code for a while and new to tkinter. The purpose of my code is to display text within the Canvas widget not overlay a label. But unsure how to do this:
My code is as follows:
from tkinter import *
class Example(Frame):
def printLabel(self):
self.hello = []
self.hello.append('Hello')
self.hello.append('World!')
return(self.hello)
def updatePanel(self):
self.panelA.config(text="{}".format(self.printLabel()))
def __init__(self, root):
Frame.__init__(self, root)
self.buttonA()
self.viewingPanel()
def buttonA(self):
self.firstPage = Button(self, text="Print Text", bd=1, anchor=CENTER, height = 11, width = 13, command=lambda: self.updatePanel())
self.firstPage.place(x=0, y=0)
def viewingPanel(self):
self.panelA = Label(self, bg='white', width=65, height=13, padx=3, pady=3, anchor=NW, text="")
self.panelA.place(x=100, y=0)
self.cl= Canvas(self.panelA,bg='WHITE',width=165,height=113,relief=SUNKEN)
canvas_id = self.cl.create_text(15, 15, anchor="nw")
self.xb= Scrollbar(self.panelA,orient="horizontal", command=self.cl.xview)
self.xb.pack(side=BOTTOM,fill=X)
self.xb.config(command=self.cl.xview)
self.yb= Scrollbar(self.panelA,orient="vertical", command=self.cl.yview)
self.yb.pack(side=RIGHT,fill=Y)
self.yb.config(command=self.cl.yview)
self.cl.itemconfig(canvas_id,font=('Consolas',9), text="{}".format(self.printLabel()))
self.cl.configure(scrollregion = self.cl.bbox("all"))
self.cl.config(xscrollcommand=self.xb.set, yscrollcommand=self.yb.set)
self.cl.config(width=250,height=150)
self.cl.pack(side=LEFT,expand=True,fill=BOTH)
def main():
root = Tk()
root.title("Tk")
root.geometry('378x176')
app = Example(root)
app.pack(expand=True, fill=BOTH)
root.mainloop()
if __name__ == '__main__':
main()
The Hello World! should display without the brackets in the Canvas but the main issue is that when I click on the Button it just overlaps the canvas and prints out the append on to the Label.
The Label should be inside the Canvas.
Here's how to fix the "main issue" along with the "brackets issue". The latter is taken care of by using the string join() method as suggested in the comments.
The updatePanel() method has been modified so it first create a Label widget with the text you want displayed in it, followed by a Canvas "window" object specifying that widget as its contents. Code for the way you were attempting to do it was also removed from the other class methods.
from tkinter import *
class Example(Frame):
def __init__(self, root):
Frame.__init__(self, root)
self.buttonA()
self.viewingPanel()
def printLabel(self):
text = []
text.append('Hello')
text.append('World!')
return ' '.join(text)
def updatePanel(self):
label = Label(self, bg='white', padx=3, pady=3, anchor=NW,
text=self.printLabel())
label.place(relx=0.5, rely=0.5, anchor=CENTER)
self.cl.create_window(100, 100, window=label) # Put Label in a Canvas "window".
def buttonA(self):
self.firstPage = Button(self, text="Print Text", bd=1, anchor=CENTER, height=11,
width=13, command=lambda: self.updatePanel())
self.firstPage.place(x=0, y=0)
def viewingPanel(self):
self.panelA = Label(self, bg='white', width=65, height=13, padx=3, pady=3,
anchor=NW, text="")
self.panelA.place(x=100, y=0)
self.cl= Canvas(self.panelA, bg='WHITE', width=165, height=113, relief=SUNKEN)
canvas_id = self.cl.create_text(15, 15, anchor="nw")
self.xb= Scrollbar(self.panelA,orient="horizontal", command=self.cl.xview)
self.xb.pack(side=BOTTOM, fill=X)
self.xb.config(command=self.cl.xview)
self.yb= Scrollbar(self.panelA, orient="vertical", command=self.cl.yview)
self.yb.pack(side=RIGHT, fill=Y)
self.yb.config(command=self.cl.yview)
self.cl.itemconfig(canvas_id, font=('Consolas',9), text=self.printLabel())
self.cl.configure(scrollregion=self.cl.bbox("all"))
self.cl.config(xscrollcommand=self.xb.set, yscrollcommand=self.yb.set)
self.cl.config(width=250, height=150)
self.cl.pack(side=LEFT, expand=True, fill=BOTH)
def main():
root = Tk()
root.title("Tk")
root.geometry('378x176')
app = Example(root)
app.pack(expand=True, fill=BOTH)
root.mainloop()
if __name__ == '__main__':
main()
I am trying to open a popup window on a click. The same is not getting opened as a popup, but another tab in the already opened window. Also, when I maximize the window the click function doesn't work at all.
My code is as under:
from tkinter import *
from tkinter import ttk
import shelve
import pyperclip
import os
def popupmsg(msg):
popup = Tk()
popup.wm_title("!")
label = ttk.Label(popup, text=msg)
label.pack(side="top", fill="x", pady=10)
B1 = ttk.Button(popup, text="Okay", command = popup.destroy)
B1.pack()
popup.mainloop()
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("uClip - Your personal clipboard")
self.pack(fill = BOTH, expand =1)
global paste_entry
paste_entry = Entry(self)
paste_entry.grid(row=1, sticky="e")
global copy_entry
copy_entry = Entry(self)
copy_entry.grid(row=2, sticky="e")
global delete_entry
delete_entry = Entry(self)
delete_entry.grid(row=3, sticky="e")
button1 = Button(self, text="Paste to uClip", command= lambda:popupmsg("Pop Up")).grid(row=1,column=1)
button2 = Button(self, text="Copy from uClip", command=None).grid(row=2,column=1)
button4 = Button(self, text="Delete from uClip",command=None).grid(row=3, column=1)
button3 = Button(self, text="List all Keywords",command=None).grid(row=4, sticky="e")
button5 = Button(self, text="Clear uClip",command=None).grid(row=5, sticky="e")
root = Tk()
root.geometry("400x300")
root.resizable(None, None)
uClip = Window(root)
root.mainloop()
I'm trying to make the buttons on my program to perform an action but I'm not 100% how to do that. I've created the buttons hopefully their correct, but just need some advice on how to make them work ! so when i click the button "add rect" it should add a random rectangle in a random position vice versa for remove.
from tkinter import *
import random
root = Tk()
class Recta:
def __init__(self, height, width):
self.height=60
self.width=80
def randomRects(self,canvas):
w = random.randrange(80)
h = random.randrange(60)
canvas.create_rectangle(0,0,h,w,fill='green')
def create_buttons(self,canvas):
frame = Frame(root, bg='grey', width=400, height=40)
frame.pack(fill='x')
frame = Frame(root, bg='grey', width=400, height=40)
frame.pack(fill='x')
button1 = Button(frame, text='Add Rect')
button1.pack(side='left', padx=10)
button2 = Button(frame, text='Remove Rect')
button2.pack(side='left')
def removeRects(self,canvas):
self.myRect = canvas.create_rectangle(0, 0, w, h, fill='green')
canvas.delete(self.myRect)
c = Canvas(root)
c.pack()
tes = Recta(10,20)
tes.randomRects(c)
tes.create_buttons(1)
root.mainloop()
Your code needed serious reorganization.
Here is something that works to add rectangles. you did not provide a remove rectangle method, so i let you write it - at this moment, the delete button calls randomRect; you likely will need to keep track of the rectangles you create in a collection of some sort in order to be able to remove them.
from tkinter import *
import random
root = Tk()
class Recta:
def __init__(self, height=60, width=80):
self.height = height
self.width = width
self.create_buttons()
self.canvas = Canvas(root)
self.canvas.pack()
def create_buttons(self):
self.frame = Frame(root, bg='grey', width=400, height=40)
self.frame.pack(fill='x')
self.button1 = Button(self.frame, text='Add Rect', command=self.randomRects)
self.button1.pack(side='left', padx=10)
self.button2 = Button(self.frame, text='Remove Rect', command=self.randomRects)
self.button2.pack(side='left')
def randomRects(self):
w = random.randrange(300)
h = random.randrange(200)
self.canvas.create_rectangle(0, 0, w, h, fill='green')
tes = Recta()
root.mainloop()