How to remove a button in a tkinter - python-3.x

The problem is that if I want to remove these buttons, which have been allocated space by x and y, it cannot be and does not generate any error or anything else shows as if it did not do any comedy, and when the button is normal it works as it should
import tkinter as t
root = t.Tk()
def click():
button.pack_forget()
root.maxsize(375, 912)
img = t.PhotoImage(file="background.png")
background = t.Label(root, image=img)
background.pack()
button = t.Button(root, text ="Click\nme", command=click)
button.pack()
button.place(x=157, y=600)
root.mainloop()

Related

Insert an image in a labelFrame title with tkinter

I wonder if it's possible to insert an image or icon in the title of a Labelframe in tkinter ?
Maybe something like this lf = Labelframe(root, image='my_img'), the same as we can do with a button.
It would be very useful.
You can insert any widget as labelwidget option of LabelFrame.
If you want an image instead of text displayed in LabelFrame:
import tkinter as tk
from PIL import Image, ImageTk
w = tk.Tk()
w.geometry("400x500")
img_open = Image.open("example_1.png")
img = ImageTk.PhotoImage(img_open)
label_title = tk.Label(w, image=img) #important Do Not grid/pack/place it!
label_frame = tk.LabelFrame(w, labelwidget=label_title)
label_frame.grid(row=0, column=0)
#fill LabelFrame with something to make it visible
bt = tk.Button(label_frame, text="Press")
bt.grid(padx=20, pady=20)
w.mainloop()
Output:
Or like I said before you can use any widget.
An example label with image and a label with text.
import tkinter as tk
from PIL import Image, ImageTk
w = tk.Tk()
w.geometry("400x500")
img_open = Image.open("example_1.png")
img = ImageTk.PhotoImage(img_open)
frame_labelwidget = tk.Frame(w) #important Do Not grid/pack/place it!
label_image = tk.Label(frame_labelwidget, image=img)
label_image.grid(row=0, column=0)
label_text = tk.Label(frame_labelwidget, text="Teamwork")
label_text.grid(row=0, column=1)
label_frame = tk.LabelFrame(w, labelwidget=frame_labelwidget)
label_frame.grid(row=0, column=0)
#fill LabelFrame with something to make it visible
bt = tk.Button(label_frame, text="Press")
bt.grid(padx=20, pady=20)
w.mainloop()
Output:
Of course that makes less sense because you can have text and an image combined in tk.Label by using compound option.
I added it only for demonstration purpose, you can add any widget you want. Instead of label_text you could add an Entry, Canvas...

Python: TypeError: 'Label' object is not callable

from PIL import Image, ImageTk
from tkinter import *
from tkinter import Label
def open_window():
menu = Toplevel(root)
menu.geometry("800x800")
menu.title("my game's menu")
menu.resizable(False, False)
menu.geometry("800x800")
lbl = Label(menu, text ="Hello!").pack
menu.mainloop()
root = Tk()
root.geometry("400x300")
Label = Label(root, text="Are you ready?")
Label.pack()
root.title("quick question")
btn = Button(root, text="Yes", command= open_window)
btn.pack(padx=20, pady = 20)
root.mainloop()
I got this error while I was working on previously seen code: File "C:\Users\User\Desktop\naujas zaidimas\scratch.py", line 11, in open_window
lbl = Label(menu, text ="Hello!").pack
TypeError: 'Label' object is not callable
Does anyone know why/how to fix it?
The code has a number of fairly obvious errors and one insidious error
This import plays no role in current code
from PIL import Image, ImageTk
Not a good or preferred way to import tkinter
This will cause problems later on
from tkinter import *
This is unnecessary with the current inport method
from tkinter import Label
def open_window():
The rule for Python functions is: Names created in functions stay in functions.
It will require a global instruction to make 'menu' available elsewhere in your code
menu = Toplevel(root)
menu.geometry("800x800")
menu.title("my game's menu")
menu.resizable(False, False)
Duplicated geometry instruction
menu.geometry("800x800")
This object has already been defined as a Label object so trying to name it throws a TypeError
lbl = Label(menu, text ="Hello!").pack()
This is unnecessary since root.mainloop() has already been executed
menu.mainloop()
root = Tk()
root.geometry("400x300")
Here is another naming problem caused by the import method chosen
Label = Label(root, text="Are you ready?")
Label.pack()
root.title("quick question")
This button will enable you to create MANY Toplevel windows
The problem is, ALL of them will be called 'menu'!?
This is the insidious error
btn = Button(root, text="Yes", command= open_window)
btn.pack(padx=20, pady = 20)
root.mainloop()
# This solution avoids all the previous problems
import tkinter as tk
root = tk.Tk()
root.title("quick question")
root.geometry("400x300")
tk.Label(root, text = "Are you ready?").pack()
# This will give tkinter time to process the given instructions.
root.update()
menu = tk.Toplevel(root)
# withdraw will make menu temporarily invisible
menu.withdraw()
menu.title("my game's menu")
menu.geometry("800x800")
menu.resizable(False, False)
tk.Label(menu, text = "Hello!").pack()
# command will now make menu window visible
btn = tk.Button(root, text = "Yes", command = menu.deiconify)
btn.pack(padx = 20, pady = 20)
root.mainloop()
from PIL import Image, ImageTk
from tkinter import *
def open_window():
menu = Toplevel(root)
menu.geometry("800x800")
menu.title("my game's menu")
menu.resizable(False, False)
menu.geometry("800x800")
lbl = Label(menu, text ="Hello!").pack()
menu.mainloop()
root = Tk()
root.geometry("400x300")
lbl1 = Label(root, text="Are you ready?").pack()
root.title("quick question")
btn = Button(root, text="Yes", command= open_window)
btn.pack(padx=20, pady = 20)
root.mainloop()
I Played around both our codes and now somewhy it works.

How to get input from tkinter Entry widget on second window while the first window continues to run

from tkinter import *
def first():
root1 = Tk()
Button(root1, text = 'get Second', command= second).pack()
root1.mainloop()
def second():
root2 = Tk()
user_input = StringVar()
Entry(root2, text = user_input).pack()
Button(root2, text = 'submit', command = lambda : print(user_input.get(), '\t printed')).pack()
root2.mainloop()
first()
You are making a few basic mistakes in here -
You if want to use a second window, it should be Toplevel not root Tk window. There should be only one root window in the program. This should act as parent to all the windows.
Its a good practice in most of the cases to define the widgets like Button, Entry separately and then pack() them.
Entry should have 'textvariable' not 'text'
Following is the updated code which may help you -
from tkinter import *
root = Tk()
def first():
button = Button(root, text = 'get Second', command= second)
button.pack()
root.mainloop()
def second():
window2 = Toplevel(root)
user_input = StringVar()
entry = Entry(window2, textvariable=user_input)
entry.pack()
button = Button(window2, text = 'submit', command = lambda: print(user_input.get()))
button.pack()
first()

tkinter - display random image from array on button click

I would like a label to display a random image when a button is clicked.
This is my approach, but it does not work. Any ideas on how to solve welcome.
from tkinter import *
import random
window = Tk()
filechoices = ["image1.png", "image2.png", "image3.png"]
filename = PhotoImage(file = random.choice[filechoices])
def press():
image = Label(window, image=filename).pack()
button1 = Button(window, text="click to see image", command = press)
button1.pack()
random.choice is a function,not a list.
It should be:
filename = PhotoImage(file = random.choice(filechoices))
Read random module
random.choice(seq)
Return a random element from the non-empty sequence seq.
Also,in your code,you haven't used mainloop()

python3 & tkinter - creating a zoom button to zoom on the loaded image

I would like to create a zoom button. On clicking on that zoom button, the image would be zoomed in by a factor represented by an integer (1,2,3,4,5...). With this piece of code, by clicking on the zoom button, another panel is created underneath the already loaded picture. Inside it is blank. What would be needed is to:
1. kill the first (non-zoomed window) and 2. load the zoomed image on the updated panel
from tkinter import *
from tkinter.filedialog import askopenfilename
import tkinter as tk
event2canvas = lambda e, c: (c.canvasx(e.x), c.canvasy(e.y))
root = Tk()
#setting up a tkinter canvas with scrollbars
frame = Frame(root, bd=2, relief=SUNKEN)
frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)
xscroll = Scrollbar(frame, orient=HORIZONTAL)
xscroll.grid(row=1, column=0, sticky=E+W)
yscroll = Scrollbar(frame)
yscroll.grid(row=0, column=1, sticky=N+S)
canvas = Canvas(frame, bd=0, xscrollcommand=xscroll.set,yscrollcommand=yscroll.set)
canvas.grid(row=0, column=0, sticky=N+S+E+W)
xscroll.config(command=canvas.xview)
yscroll.config(command=canvas.yview)
frame.pack(fill=BOTH,expand=1)
#adding the image
image_str="image.png"
image = tk.PhotoImage(file=image_str)
image = image.zoom(1,1)
canvas.create_image(0,0,image=image,anchor="nw")
canvas.config(scrollregion=canvas.bbox(ALL))
def zoomin():
root = Tk()
frame = Frame(root, bd=2, relief=SUNKEN)
frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)
xscroll = Scrollbar(frame, orient=HORIZONTAL)
xscroll.grid(row=1, column=0, sticky=E+W)
yscroll = Scrollbar(frame)
yscroll.grid(row=0, column=1, sticky=N+S)
canvas = Canvas(frame, bd=0, xscrollcommand = xscroll.set, yscrollcommand = yscroll.set)
canvas.grid(row=0, column=0, sticky=N+S+E+W)
xscroll.config(command=canvas.xview)
yscroll.config(command=canvas.yview)
frame.pack(fill=BOTH,expand=1)
image = tk.PhotoImage(file=image_str)
image = image.zoom(1,1)
canvas.create_image(0,0,image=large_img,anchor="nw")
canvas.config(scrollregion=canvas.bbox(ALL))
toolbar = Frame(root, bg="blue")
insertButt = Button(toolbar, text="zoomin", command=lambda:zoomin())
insertButt.pack(side = LEFT, padx=2, pady=2)
toolbar.pack(side=TOP, fill = X)
#function to be called when mouse is clicked
def printcoords(event):
#outputting x and y coords to console
print (event.x,event.y)
#mouseclick event
canvas.bind("<Button 1>",printcoords)
#mouseclick event
canvas.bind("<ButtonPress-1>",printcoords)
canvas.bind("<ButtonRelease-1>",printcoords)
root.mainloop()
I would like to thank #Symon for his stackoverflow question. I largely inspired myself from his code
Well, the reason that the function zoomin(img) does not work properly is that it returns in the first line:
def zoomin(img):
return # Function returns here
... rest of code is never executed
I suspect this is due to the function being run when you create the button, not when you press it. Try cretating the button in this way instead:
insertButt = Button(toolbar, text="zoomin", command=lambda:zoomin(img))
Now the button will call zoomin(img) when it's pressed and not when the button is created.
Zooming with Tkinter
PhotoImage zoom only allows integer values, wich makes it a bit limited. But here's an example:
from tkinter import *
root = Tk()
root.geometry('300x200')
field = Canvas(root, bg='tan1', highlightthickness=0)
field.grid(sticky='news')
photo = PhotoImage(file='test.gif')
field.create_image(0, 0, image=photo, anchor='nw')
scale = 1
def zoom(event=None):
global scale, photo
scale = scale * 2
field.delete('all')
photo = photo.zoom(x=scale, y=scale)
field.create_image(0, 0, image=photo, anchor='nw')
field.image = photo
root.bind('z', zoom) # Bind "z" to zoom function
root.mainloop()
If you want to zoom by float you'll have to import a module for that. Pillow seems popular. But I haven't worked with any of them so you'll have to research them yourself.

Resources