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()
Related
I am making a text base game and would like to get a new root window on the click of a button while simultaneously closing the original one?
#Packages
import tkinter as tk
from tkinter import ttk, BOTTOM
from PIL import ImageTk, Image
#Create Window
root = tk.Tk()
root.geometry("360x740")
root.resizable(True, True)
root.title("Box")
root.configure(bg="black")
#Load Image
canvas = tk.Canvas(root, width=360, height=360, bg="black")
tk.Canvas(bg="black")
canvas.pack()
img = ImageTk.PhotoImage(Image.open("sample_image.jpg"))
canvas.create_image(180, 200, image=img)
#Create Text Widget
T = tk.Text(root, height=10, width=52, bg="black", fg="white")
l = tk.Label(root, text="Hard Living by Amsha", fg="white", bg="black")
l.config(font=(None, 14,))
story = """
"""
l.pack()
T.pack()
#Continue Button
yes_button = ttk.Button(root, text="Continue", command=lambda: next_window())
yes_button.pack(pady=75, side=BOTTOM)
T.insert(tk.END, story)
root.mainloop()
def next_window():
root.quit()
root = tk.Tk()
root.geometry("360x740")
root.resizable(True, True)
root.title("Hard Living")
root.configure(bg="black")
root.mainloop()
I have created a program in Python using tkinter. I have created two seperate classes for two windows. I am opening the other window by clicking on the button of one window. I want it such that when new window opens the other should close. My code is
from tkinter import Tk, Toplevel
from tkinter import *
def main():
main_window = Tk()
app = first(main_window)
main_window.mainloop()
class first:
def __init__(self, root):
self.root = root
self.root.title('First window')
self.root.geometry('1350x700+0+0')
frame1 = Frame(self.root, bg='black')
frame1.place(x=400, y=50, width=400, height=600)
btn_1 = Button(frame1, command=self.second_window, text='open second window', font=("Times New Roman", 15, 'bold'), bd=3,
relief=RIDGE,
cursor='hand2', bg='red', fg='white', activeforeground='white', activebackground='red')
btn_1.place(x=100, y=350, width=220, height=35)
def second_window(self):
self.new_window = Toplevel(self.root)
self.app = second(self.new_window)
class second:
def __init__(self, root):
self.root = root
self.root.title('Second Window')
self.root.geometry("1350x700+0+0")
self.root.config(bg='white')
frame1 = Frame(self.root, bg='black')
frame1.place(x=400, y=50, width=400, height=600)
btn_1 = Button(frame1, command=self.first_window, text='open first window',
font=("Times New Roman", 15, 'bold'), bd=3,
relief=RIDGE,
cursor='hand2', bg='red', fg='white', activeforeground='white', activebackground='red')
btn_1.place(x=100, y=350, width=220, height=35)
def first_window(self):
self.new_window = Toplevel(self.root)
self.app = first(self.new_window)
if __name__ == '__main__':
main()
I understand this question is quite common but I cant find a soloution on here which would be applicable for my code.
You can destroy the previous window and start a new window using Tk class
Here is an example
from tkinter import *
from tkinter.ttk import Button
root = Tk()
root.title("title")
root.geometry("800x500")
def window2():
root.destroy()
window2_main = Tk()
Label(window2_main, text="Bye Bye").pack()
window2_main.mainloop()
a = Button(text="Click This", command=window2)
a.pack()
root.mainloop()
This is my code:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", lambda: on_closing(root, btn))
frame1 = tk.Frame(root, bg=root['background'])
frame1.pack(expand="YES")
canvas = tk.Canvas(frame1, width=200, height=300, relief="sunken", bd=0, bg=root['background'])
scroll_y = tk.Scrollbar(frame1, orient="vertical", command=canvas.yview, bg=canvas['background'])
scroll_y.pack(side="right", fill='y')
canvas.pack(side="top", expand='YES', fill='both')
canvas.configure(yscrollcommand=scroll_y.set)
# canvas.update_idletasks()
# canvas.yview_moveto('1.0')
s = ttk.Style()
s.configure("new.TFrame", background=canvas['background'], width=canvas.winfo_width(), height=canvas.winfo_height())
msgFrame = ttk.Frame(canvas, style="new.TFrame")
msgFrame.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window=msgFrame, anchor="nw")
Why won't the frame change its color? Or its width/height?
If you'd like to put some strings in the frame:
for i in range (50):
lbl = tk.Label(msgFrame, text="example").pack()
First using same background color for all the widgets is hard to see the effect. For debug purpose, use different background colors for different widgets.
Second you cannot set the width and height of a ttk::Frame using style.configure(), specify them in ttk::Frame(...).
Below is an modified example based on your code:
import tkinter as tk
from tkinter import ttk
def on_closing(root):
root.destroy()
root = tk.Tk()
root.geometry("400x400")
root.config(bg="cyan")
root.protocol("WM_DELETE_WINDOW", lambda: on_closing(root))
frame1 = tk.Frame(root, bg="red")
frame1.pack(expand="YES")
canvas = tk.Canvas(frame1, width=200, height=300, relief="sunken", bd=0, bg="green")
scroll_y = tk.Scrollbar(frame1, orient="vertical", command=canvas.yview, bg=canvas['background'])
scroll_y.pack(side="right", fill='y')
canvas.pack(side="top", expand='YES', fill='both')
canvas.configure(yscrollcommand=scroll_y.set)
s = ttk.Style()
s.configure("new.TFrame", background="blue")
msgFrame = ttk.Frame(canvas, style="new.TFrame", width=100, height=200) # set width and height
msgFrame.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window=msgFrame, anchor="nw")
root.mainloop()
And the output:
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'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()