I want to allow the user to create as many labels as they want using the following code:
def new_line(event):
global Row_n
Row_n = Row_n + 1
Choose= tk.Label(frame, text="Choose option", background = "white",font = ("Helvetica",13),fg = "blue")
Choose.grid(row = Row_n, column = 0, sticky = 'nsew')
return Row_n
root.bind('<Return>',lambda event:new_line(event))
That way, by pressing "Enter", the user can create as many "Choose" labels as they wish. But then I want for a second label to appear every time the user clicks on one of the "Choose" label. So I use the following code:
def second_l(event):
Row_n = Row_n+1
second_label = tk.Label(frame, text="Second label")
Choose.bind('<Button-1>',lambda event:second_l(event))
When I try to run this I get the following error:
can't invoke "bind" command: application has been destroyed
If I add "Choose" label outside the "new_line" function the "second_l" function will only work for that label. It won´t work for the labels generated by the "new_line" function.
Whole code:
import tkinter as tk#to create the gui
from tkinter import filedialog, Text #filedialog to pick apps and Text to display text
import os #Allows us to run apps
root = tk.Tk()
frame = tk.Frame(root,bg="white")
frame.place(relwidth=0.8,relheight=0.7,relx=0.1,rely=0.1)
Row_n=0
def new_line(event):
global Row_n
Row_n = Row_n + 1
Choose= tk.Label(frame, text="Choose option", background = "white",font = ("Helvetica",13),fg = "blue")
Choose.grid(row = Row_n, column = 0, sticky = 'nsew')
return Row_n
root.bind('<Return>',lambda event:new_line(event))
def second_l(event):
global Row_n
Row_n = Row_n+1
second_label = tk.Label(frame, text="Second label")
second_label.grid(row = Row_n, column = 0, sticky = 'nsew')
Choose.bind('<Button-1>',lambda event:second_l(event))
root.mainloop()
I am unable to understand why are you getting this error "can't invoke "bind" command" but I think, I understand your problem
you can try this:-
import tkinter as tk#to create the gui
from tkinter import filedialog, Text #filedialog to pick apps and Text to display text
import os #Allows us to run apps
root = tk.Tk()
frame = tk.Frame(root,bg="white")
frame.place(relwidth=0.8,relheight=0.7,relx=0.1,rely=0.1)
Row_n=0
Choose= tk.Label(frame, text="", background = "white",font = ("Helvetica",13),fg = "blue")
def new_line(event):
global Row_n
Row_n = Row_n + 1
Choose.config(text="Choose option")
Choose.grid(row = Row_n, column = 0, sticky = 'nsew')
return Row_n
root.bind('<Return>',lambda event:new_line(event))
def second_l(event):
global Row_n
Row_n = Row_n+1
second_label = tk.Label(frame, text="Second label")
second_label.grid(row = Row_n, column = 0, sticky = 'nsew')
Choose.bind('<Button-1>',lambda event:second_l(event))
root.mainloop()
Related
Running python 3.8 in PyCharm
I'm trying to create a class to allow creation of a tkinter checkbutton (and eventually other widgets) that will hold all the formatting and definition for the widget. I would like to be able to test the state of the checkbutton and act on it in a callback. But like many others, my checkbutton variable seems to always be 0. I'm fairly sure its a garbage collection issue, but I can't figure a way around it. Note the second set of parameters in the class definition specify the location of the label to display the checkbutton variable state. At the moment, the callback is just to display the variable state in a label.
Acknowledgement:
I modified code from Burhard Meier's book "Python GUI Programming Cookbook" for this. The code related to the class is mine, the rest is from Burkhard Meier.
'''
This is a modification of code by Burhard A. Meier
in "Python GUI Programming Cookbook"
Created on Apr 30, 2019
#author: Burkhard A. Meier
'''
#======================
# imports
#======================
import tkinter as tk
from tkinter import ttk
# Create instance
win = tk.Tk()
# Add a title
win.title("GUI Test Box")
# Modify adding a Label
a_label = ttk.Label(win, text="Testing TK Widgets")
a_label.grid(column=0, row=0)
# Modified Button Click Function
def click_me():
action.configure(text='Hello ' + name.get() + ' ' +
number_chosen.get())
#Define the Checkbutton Class
class ChkBut(): #lable, xloc, yloc, xlab, ylab
def __init__(self, lable, xloc, yloc, xlab, ylab): # , xloc, yloc, text="default", variable = v, onvalue='Set', offvalue='NotSet'):
v = tk.IntVar()
self.v = v
self.lable = lable
self.xloc = xloc
self.yloc = yloc
self.xlab = xlab
self.ylab = ylab
c = tk.Checkbutton(
win,
text= self.lable,
variable=self.v,
command=self.cb(self.v, xlab,ylab))
c.grid(column=xloc, row=yloc, sticky = tk.W)
c.deselect()
def cb (self, c, xlab, ylab):
if c.get()==1:
c_label = ttk.Label(win, text="Set")
c_label.grid(column=xlab, row=ylab)
elif c.get()==0:
c_label = ttk.Label(win, text="NotSet")
c_label.grid(column=xlab, row=ylab)
else:
c_label = ttk.Label(win, text=c.v.get())
c_label.grid(column=xlab, row=ylab)
# Changing the Label
ttk.Label(win, text="Enter a name:").grid(column=0, row=0)
# Adding a Textbox Entry widget
name = tk.StringVar()
name_entered = ttk.Entry(win, width=12, textvariable=name)
name_entered.grid(column=0, row=1)
# Adding a Button
action = ttk.Button(win, text="Click Me!", command=click_me)
action.grid(column=2, row=1)
# Creating three checkbuttons
ttk.Label(win, text="Choose a number:").grid(column=1, row=0)
number = tk.StringVar()
number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly')
number_chosen['values'] = (1, 2, 4, 42, 100)
number_chosen.grid(column=1, row=1)
number_chosen.current(0)
check1 = ChkBut("Button 1", 0, 4, 0, 5)
chVarUn = tk.IntVar()
check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn)
check2.deselect()
check2.chVarUn = 0
check2.grid(column=1, row=4, sticky=tk.W)
chVarEn = tk.IntVar()
check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn)
check3.select()
check3.chVarEn = 0
check3.grid(column=2, row=4, sticky=tk.W)
name_entered.focus() # Place cursor into name Entry
#======================
# Start GUI
#======================
win.mainloop()
Can you please help me with follwing issue I face:
When I am creating radiobutton with tkinter, I don't have a problem to select from the list.
However, if I put the same script under a menu, then selected option is always the default one, ("Python",1) in this specific case. Do you have any idea how to overcome this? Thanks in advance!
import tkinter as tk
root_m = tk.Tk()
root_m.geometry("400x200")
frame_m = tk.Frame(root_m)
root_m.title("NUMERIC UNIVERSE")
frame_m.pack()
def chars_merging():
languages = [
("Python",1),
("Perl",2),
("Java",3),
("C++",4),
("C",5)
]
root = tk.Tk()
root.geometry("400x200")
frame = tk.Frame(root)
root.title("SELECT SOMETHING")
frame.pack()
v = tk.IntVar()
v.set(0) # initializing the choice, i.e. Python
label = tk.Label(frame,
text="""Choose your favourite
programming language:""",
justify = tk.LEFT,
padx = 20)
label.pack()
def ShowChoice():
global data_sel
data_sel = v.get()
print(data_sel)
for val, language in enumerate(languages):
tk.Radiobutton(frame,
text=language,
indicatoron = 0,
width = 20,
padx = 20,
variable=data_sel,
command=ShowChoice,
value=val).pack(anchor=tk.W)
root.mainloop()
#return(languages[v.get()])
print("You selected", languages[v.get()])
button3 = tk.Button(frame_m,
text="3.Prepare and merge chars",
command=chars_merging,
width=25)
button3.pack()
# CLOSING THE WINDOW ---------------------------------------------------------
def finish():
root_m.destroy()
button_n = tk.Button(frame_m,
text="Finish",
command=finish,
width=25)
button_n.pack()
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
root_m.mainloop()
I have a Submit button that prints the output on the tkinter widget label. Everytime I change the input and click the Submit the output is displayed but not at the same place i.e. The previous content of the label is not overwritten.
from tkinter import *
from tkinter import filedialog
root = Tk()
root.title("ImageValidation ")
root.geometry("600x600+100+100")
pathlist = [None, None] # holds the two files selected
labels = []
def browse_button(index):
global filename
filename = filedialog.askopenfilename(title = "Choose your file",filetypes = (("jpeg files","*.jpeg"),("all files","*.*")))
pathlist[index] = filename
heading = Label(root, text = "Select 2 images you want to Validate",
font=("arial",15,"bold","underline"), fg="blue").pack()
label1 = Label(root, text = "Enter Image 1", font=("arial",10,"bold"),
fg="black").place(x=10, y = 100)
label2 = Label(root, text = "Enter Image 2", font=("arial",10,"bold"),
fg="black").place(x=10, y = 200)
button = Button(root,text="Choose an Sign1",width = 30,command= lambda:
browse_button(0)).place(x=250, y= 100)
button = Button(root,text="Choose an Sign2",width = 30,command=
lambda: browse_button(1)).place(x=250, y= 200)
def display():
ImageVerification(pathlist[0], pathlist[1])
l1 = Label(root,text=Scriptoutput, width = 200 )
l1.pack(side='bottom', padx=50, pady=50)
#Scriptoutput is the output variable from the main code.
submit_button = Button(text="Submit", width=15,command = display)
submit_button.pack(side='bottom', padx=15, pady=15)
root.mainloop()
A 'refresh' button that would clear the Label of its content and lets you overwrite it.
I am taking your function ImageVerification() as a blackbox and assuming it is working.
The reason this is happening is because you create a new Label, whenever the Submit button is pressed. What you have to do is to create the display Label outside the function and configure its text, whenever the button is pressed. Something like this.
l1 = Label(root, text="", width=200)
l1.pack(side='bottom', padx=50, pady=50)
def display():
ImageVerification(pathlist[0], pathlist[1])
l1.configure(text=Scriptoutput)
#Scriptoutput is the output variable from the main code.
submit_button = Button(text="Submit", width=15,command = display)
submit_button.pack(side='bottom', padx=15, pady=15)
I am working on a Tkinter app that takes input and outputs excel data. I cannot get the entry for size or any other entry field. I want the entry to be obtained and stored in the excel file when the user selects finish order. What change does the code need?
so far everything works except that I do not know how to get the data from the entry because when the button is clicked it runs the code again and thus erases the values.
import datetime
import tkinter as tk
import xlwt as xl
from datetime import datetime
style1 = xl.XFStyle()
style1.num_format_str = "D-MM-YY"
wb = xl.Workbook()
sheet1 = wb.add_sheet("Sheet1", cell_overwrite_ok=True)
sheet1.write(0, 0, datetime.now(), style1)
sheet1.write(0, 1, "Item")
sheet1.write(0, 2, "Size")
sheet1.write(0, 3, "Quantity")
window = tk.Tk()
window.geometry("500x500")
window.title("Furniture order")
item_label = tk.Label(text="Select your item ")
item_label.grid(column= 5, row=0)
def destroy ():
item_label.destroy()
table_button.destroy()
chair_button1.destroy()
def options ():
size_label = tk.Label(text="Enter the size")
size_label.grid(column=0, row=0)
color_label = tk.Label(text="Enter the color")
color_label.grid(column=0, row=1)
quantity_label = tk.Label(text="Enter the quantity")
quantity_label.grid(column=0, row=2)
done_button = tk.Button(text="Finish the order", command=get_data)
done_button.grid(column=1, row=4)
def entry ():
size_entry = tk.Entry(window)
size_entry.grid(column=2, row=0)
color_entry = tk.Entry()
color_entry.grid(column=2, row=1)
quantity_entry = tk.Entry()
quantity_entry.grid(column=2, row=2)
return size_entry.get()
def get_data ():
size = entry()
sheet1.write(1, 1, "table")
sheet1.write(1, 2, size)
wb.save("test2.xls")
def t_d ():
destroy()
options()
entry()
def c_d ():
destroy()
options()
entry()
chair_button1 = tk.Button(text="Chair", command=t_d)
chair_button1.grid(column=0, row=3)
table_button = tk.Button(text="Table", command=c_d)
table_button.grid(column=10, row=3)
wb.save("test2.xls")
window.mainloop()
import sys
from tkinter import *
def printer():
print(message)
print(offset)
gui = Tk()
gui.title("Caesar Cypher Encoder")
Button(gui, text="Encode", command=printer).grid(row = 2, column = 2)
Label(gui, text = "Message").grid(row = 1, column =0)
Label(gui, text = "Offset").grid(row = 1, column =1)
message = Entry(gui)
message.grid(row=2, column=0)
offset = Scale(gui, from_=0, to=25)
offset.grid(row=2, column=1)
mainloop( )
When i run the above code with an input in both the input box and a value on the slider - it comes up with the ouput
.46329264
.46329296
How would i get it to display the string inputted into the text box, and the value selected on the slider
Use Entry.get, Scale.get methods:
def printer():
print(message.get())
print(offset.get())