Why don't any of my buttons work? - python

First i had the sqrt button which worked fine, and then I added the pi button, and nothing worked, i tried changing everything and i still don't know whats wrong! Please someone help.
import sys
from tkinter import *
from math import *
def sqrt_():
text = ment.get()
a = sqrt(text)
label['text'] = a
def pi_():
text = ment.get()
a = pi(text)
label_1['text'] = a
root = Tk()
root.title('Conversions')
root.geometry('400x400')
#Get square root
sqrt_button = Button(root, text='Get Square root',command= sqrt_).place(x='160', y='5')
label = Label(root, text='')
label.place(x=5, y=30)
ment = IntVar()
entry = Entry(textvariable=ment).place(x='5', y= '10 ')
#Get Pi
pi_button = Button(root, text='Get Pi',command= pi_).place(x='160', y='50')
label_1 = Label(root, text='')
label_1.place(x=55, y=200)
ment = IntVar()
entry_1 = Entry(textvariable=ment).place(x='5', y= '55 ')
root.mainloop()

First, you don't define the function pi which means when you click the second button it will fail.
Second, you redefined the ment. In this case both two entries will be bound to the same int. This means when you click the first button, it will read the value from the second entry. So change all the second ment to ment_1. The name, the name in entry and the name in pi_.
import sys
from tkinter import *
from math import *
def sqrt_():
text = ment.get()
a = sqrt(text)
label['text'] = a
def pi_():
label_1['text'] = pi
root = Tk()
root.title('Conversions')
root.geometry('400x400')
#Get square root
sqrt_button = Button(root, text='Get Square root',command= sqrt_).place(x='160', y='5')
label = Label(root, text='')
label.place(x=5, y=30)
ment = IntVar()
entry = Entry(textvariable=ment).place(x='5', y= '10 ')
#Get Pi
pi_button = Button(root, text='Get Pi',command= pi_).place(x='160', y='50')
label_1 = Label(root, text='')
label_1.place(x=55, y=200)
ment_1 = IntVar()
entry_1 = Entry(textvariable=ment_1).place(x='5', y= '55 ')
root.mainloop()

pi isn't a function it is a constant so:
def pi_():
label_1['text'] = pi

Related

Python entry to store input into a variable stores nothing, returns initial value

Ok, so basic story. I have created an entry. After you introduce text, you have to click a button to store the inputted text into a variable that is later printed.
Here is the code:
from Tkinter import *
def myClick(entry_name, var):#defines function to get input from entry and store into var
var = entry_name.get()
root = Tk()#creates initial tk
lbl1 = Label(root, text = "hello")#before entry label
lbl1.grid(row = 0, column = 0)#label griding
ent = Entry(root, width = 15)# the entry
ent.grid(row = 1, column = 0)#entry gridding
hello = None #variable to store entry input
bt1 = Button(root, command = myClick(ent, hello))#button 1 creation and function attribution
bt1.grid(row = 3, column = 0)#button 1 griding
root.mainloop()
print(hello)
It is very unclear to me why the function does not get the input from the entry.
bt1 = Button(root, command = myClick(ent, hello))
In this line, you call myClick function with parameters, not just pass it. That means that myClick is executed once after the module is launched and then it does nothing. If you want to print the entry input, I recommend you do the following:
from tkinter import *
root = Tk()
lbl1 = Label(root, text="hello")
lbl1.grid(row=0, column=0)
ent = Entry(root, width=15)
ent.grid(row=1, column=0)
def myClick():
var = ent.get()
print(var)
bt1 = Button(root, command=myClick)
bt1.grid(row=3, column=0)
root.mainloop()
Also code after root.mainloop() doesn't excecute.
just define a normal function :
from tkinter import *
def blinta():
var = ent.get()
ent.delete(0,END)
print(var)
root = Tk()#creates initial tk
lbl1 = Label(root, text = "hello")#before entry label
lbl1.grid(row = 0, column = 0)#label griding
ent = Entry(root, width = 15)# the entry
ent.grid(row = 1, column = 0)#entry gridding
bt1 = Button(root, command = blinta)
bt1.grid(row = 3, column = 0)
root.mainloop()
This will work I'm sure.

How to clear a label using tkinter when pressing a button?

I am using labels to show a generated password in my tkinter password generator program, but when I change the length of a password from a lower value than before (for example from a length of 20 to 10) the label displaying the password appears to be overwritten - it does not clear. I have searched methods to do this, but I cannot seem to find any.
Here is my code:
from tkinter import *
from random import *
import string
root = Tk()
root.wm_title("Password Generator")
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
root.geometry("1000x1000")
title = Label(topFrame, text="Length", fg="blue")
title.grid(row=3,column=5)
var = DoubleVar()
Slider_1 = Scale(root,orient=HORIZONTAL,length=32*10,from_=0,to=32, variable
= var)
Slider_1.pack()
passLen = var.get()
uppercaseLetters = "QWERTYUIOPASDFGHJKLZXCVBNM"
lowercaseLetters = "qwertyuiopasdfghjklzxcvbnm"
symbols = "!£$%^&*()_+-=}{][~##':;?>/.<,"
digits = "1234567890"
def gen():
characters = uppercaseLetters + lowercaseLetters + symbols + digits
password = "".join(choice(characters) for x in range(int(var.get())))
passLabel = Label(topFrame, text=password)
passLabel.grid(row=4, column=5)
genButton = Button(topFrame, text="Generate Password", fg="blue",
command=gen)
genButton.grid(row=1, column=5)
root.mainloop()
When I set the length to 32 characters:
And when I set the length to 6 characters it does not clear the old password label - it simply overwrites it in the middle of the old password label:
First of all, move your gen method definition to just below imports so that they're recognized in the main body. Then take your widgets and mainloop out of the method. Just configure passLabel's text when needed:
def gen():
characters = uppercaseLetters + lowercaseLetters + symbols + digits
password = "".join(choice(characters) for x in range(int(var.get())))
passLabel['text'] = password
Entire code with suggested edits been made:
from tkinter import *
from random import *
import string
def gen():
characters = uppercaseLetters + lowercaseLetters + symbols + digits
password = "".join(choice(characters) for x in range(int(var.get())))
passLabel['text'] = password
root = Tk()
root.wm_title("Password Generator")
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
root.geometry("1000x1000")
title = Label(topFrame, text="Length", fg="blue")
title.grid(row=3,column=5)
var = DoubleVar()
Slider_1 = Scale(root,orient=HORIZONTAL,length=32*10,from_=0,to=32, variable
= var)
Slider_1.pack()
passLen = var.get()
uppercaseLetters = "QWERTYUIOPASDFGHJKLZXCVBNM"
lowercaseLetters = "qwertyuiopasdfghjklzxcvbnm"
symbols = "!£$%^&*()_+-=}{][~##':;?>/.<,"
digits = "1234567890"
passLabel = Label(topFrame)
passLabel.grid(row=4, column=5)
genButton = Button(topFrame, text="Generate Password", fg="blue",
command=gen)
genButton.grid(row=1, column=5)
root.mainloop()
Change two things:
First:
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
passLabel = Label(topFrame)
root.geometry("1000x1000")
Second:
def gen():
characters = uppercaseLetters + lowercaseLetters + symbols + digits
password = "".join(choice(characters) for x in range(int(var.get())))
passLabel.config(text=password)
passLabel.grid(row=4, column=5)
"How to clear a label using tkinter when pressing a button?"
Below is an example that clears label's text when the button is pressed:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def clear_widget_text(widget):
widget['text'] = ""
if __name__ == '__main__':
root = tk.Tk()
label = tk.Label(root, text="This will be cleared.")
button = tk.Button(root, text="Clear",
command=lambda : clear_widget_text(label))
label.pack()
button.pack()
root.mainloop()
Below is an example that destroys label when button is pressed:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def clear_widget(widget):
widget.destroy()
if __name__ == '__main__':
root = tk.Tk()
label = tk.Label(root, text="This will be cleared.")
button = tk.Button(root, text="Clear",
command=lambda : clear_widget(label))
label.pack()
button.pack()
root.mainloop()

Python - Tkinter - Label Not Updating

Any ideas why the leftresult_label label does not update? The function seems to work but the label does not update. I have looked everywhere and can't find an answer. The 'left' value gets set but the label does not change.
from tkinter import *
root = Tk(className="Page Calculator")
read = IntVar()
total = IntVar()
left = IntVar()
read.set(1)
total.set(1)
left.set(1)
read_label = Label(root,text="Pages Read:")
read_label.grid(column=1, row=1)
total_label = Label(root,text="Total Pages:")
total_label.grid(column=1, row=2)
read_entry = Entry(root,textvariable=read)
read_entry.grid(column=2, row=1)
total_entry = Entry(root,textvariable=total)
total_entry.grid(column=2, row=2)
def func1():
left.set(total.get() - read.get())
print(left.get())
calculate_button = Button(root,text="Calculate",command= func1)
calculate_button.grid(column=2, row=3)
percenet_label = Label(root,text="Percent Finished:")
percenet_label.grid(column=1, row=4)
left_label = Label(root,text="Pages Left:")
left_label.grid(column=1, row=5)
percenetresult_label = Label(root,text=left.get())
percenetresult_label.grid(column=2, row=4)
leftresult_label = Label(root,text="")
leftresult_label.grid(column=2, row=5)
root.mainloop()
To make the function do the job, you'd rather have your label:
leftresult_label = Label(root, textvariable=left)
Once it's tkinter class variable, tkinter takes care about when you change the value. Once you click the button,
def func1():
left.set(total.get() - read.get())
percent.set(int(read.get()*100/total.get()))
left and percent values, which are instances of tkinter.IntVar() class have immidiate effect on widgets (labels in this case) where those values are set as textvariable, just as you have it at Entry widgets.
Here is full code:
from tkinter import *
root = Tk(className="Page Calculator")
read = IntVar()
total = IntVar()
left = IntVar()
percent = IntVar()
read.set(1)
total.set(1)
left.set(1)
percent.set(1)
def func1():
left.set(total.get() - read.get())
percent.set(int(read.get()*100/total.get()))
read_label = Label(root,text="Pages Read:")
read_label.grid(column=1, row=1)
read_entry = Entry(root,textvariable=read)
read_entry.grid(column=2, row=1)
total_label = Label(root,text="Total Pages:")
total_label.grid(column=1, row=2)
total_entry = Entry(root,textvariable=total)
total_entry.grid(column=2, row=2)
calculate_button = Button(root,text="Calculate",command= func1)
calculate_button.grid(column=2, row=3)
percenet_label = Label(root,text="Percent Finished:")
percenet_label.grid(column=1, row=4)
left_label = Label(root,text="Pages Left:")
left_label.grid(column=1, row=5)
percenetresult_label = Label(root,textvariable=percent)
percenetresult_label.grid(column=2, row=4)
leftresult_label = Label(root,textvariable=left)
leftresult_label.grid(column=2, row=5)
root.mainloop()
code including progress bar. update_idletasks() used to keep label and progress bar running.
from tkinter import *
from tkinter import ttk
root = Tk()
root.title('Counter Test')
root.iconbitmap('IT.ico')
root.geometry("800x400")
def missing():
while i < 100:
progress1['value'] = i
label1.config(text=progress1['value'])
root.update_idletasks()
i += 1
progress1 = ttk.Progressbar(root, orient=HORIZONTAL, length=250, mode='determinate')
progress1.pack(pady=15)
label1 = Label(root, text="")
label1.pack(pady=15)
button_1 = Button(root, text="Missing", command=missing)
button_1.pack(pady=15)
button_q = Button(root, text="Quit", command=root.destroy)
button_q.pack(pady=15)
root.mainloop()
so to update controls immediately, like updating labels and TreeView elements this code worked for me.
window = tk.Tk()
window.update_idletasks()

Creating new entry boxes with button Tkinter

How do i make the button to add two box (side by side) below when it is being clicked as the user decided to put more input?
def addBox():
labelframe = Tkinter.Frame()
labelframe.bind("<Add Input>", callback)
labelframe.pack()
labelframe = Tkinter.Frame()
labelFrom = Tkinter.Label(labelframe, text= "from")
labelFrom.grid(column=1, row=0)
e = Tkinter.Entry(labelframe)
e.grid(column=1, row=1)
labelTo = Tkinter.Label(labelframe, text= "to")
labelTo.grid(column=2, row=0)
e2 = Tkinter.Entry(labelframe)
e2.grid(column=2, row=1)
labelframe.pack()
addboxButton = Button( root,text='<Add Time Input>', fg="Red",command="addBox")
addboxButton.pack(side=Tkinter.TOP)
This is example how to add Entry.
Probably you get problem because you use quotation marks in command=addBox
Because you will have to get values from entries you have to remeber them on list.
I add button which print text from entries.
from Tkinter import *
#------------------------------------
def addBox():
print "ADD"
ent = Entry(root)
ent.pack()
all_entries.append( ent )
#------------------------------------
def showEntries():
for number, ent in enumerate(all_entries):
print number, ent.get()
#------------------------------------
all_entries = []
root = Tk()
showButton = Button(root, text='Show all text', command=showEntries)
showButton.pack()
addboxButton = Button(root, text='<Add Time Input>', fg="Red", command=addBox)
addboxButton.pack()
root.mainloop()
#------------------------------------
EDIT:
Example with boxes side by side.
I use new frame to keep entries side by side using grid().
This way I don't mix grid() with pack() in main window/frame.
I use len(all_entries) to get number of next free column.
from Tkinter import *
#------------------------------------
def addBox():
print "ADD"
# I use len(all_entries) to get nuber of next free column
next_column = len(all_entries)
# add label in first row
lab = Label(frame_for_boxes, text=str(next_column+1))
lab.grid(row=0, column=next_column)
# add entry in second row
ent = Entry(frame_for_boxes)
ent.grid(row=1, column=next_column)
all_entries.append( ent )
#------------------------------------
def showEntries():
for number, ent in enumerate(all_entries):
print number, ent.get()
#------------------------------------
all_entries = []
root = Tk()
showButton = Button(root, text='Show all text', command=showEntries)
showButton.pack()
addboxButton = Button(root, text='<Add Time Input>', fg="Red", command=addBox)
addboxButton.pack()
frame_for_boxes = Frame(root)
frame_for_boxes.pack()
root.mainloop()
#------------------------------------
EDIT:
Another example:
from Tkinter import *
#------------------------------------
def addBox():
print "ADD"
frame = Frame(root)
frame.pack()
Label(frame, text='From').grid(row=0, column=0)
ent1 = Entry(frame)
ent1.grid(row=1, column=0)
Label(frame, text='To').grid(row=0, column=1)
ent2 = Entry(frame)
ent2.grid(row=1, column=1)
all_entries.append( (ent1, ent2) )
#------------------------------------
def showEntries():
for number, (ent1, ent2) in enumerate(all_entries):
print number, ent1.get(), ent2.get()
#------------------------------------
all_entries = []
root = Tk()
showButton = Button(root, text='Show all text', command=showEntries)
showButton.pack()
addboxButton = Button(root, text='<Add Time Input>', fg="Red", command=addBox)
addboxButton.pack()
root.mainloop()
#------------------------------------
First of all, the indentation is a whole mess, so I don't know where does the addBox function end ..
Second, I don't think you need a button, I suppose a checkbutton will do the same thing and it's also more common and familiar to users, I once had this problem and I simply created an entry box and put above it a label indicating that it's optional, and as for code, I simply ignored it if it was empty and verified the input if I found any input ..Howerver, that was for only one entry box, and you probably will need something more complex ..
See this ..
class OptionsView(Frame):
"""Frame for options in main window"""
def __init__(self, x, y, parent):
Frame.__init__(self, parent)
self.x = x
self.y = y
self.placed = False
self.hidden = False
self.btn = Button(self, text = 'Button attached to the frame ..', command = lambda: print('Button in frame clicked ..')).pack()
def pack(self):
self.place(x = self.x, y = self.y)
self.placed = True
def toggle_view(self):
if self.hidden:
self.pack()
self.hidden = False
else:
self.place_forget()
self.hidden = True
if __name__ == '__main__':
def m_frame():
if val.get() and not options_frame.placed:
print('Showing Frame ..')
options_frame.pack()
else:
print('Toggling Frame ..')
options_frame.toggle_view()
root = Tk()
root.geometry('300x400+500+600')
root.title('Testing Hiding Frames ..')
options_frame = OptionsView(200, 300, root)
val = BooleanVar(value = False)
Checkbutton(text = 'View more Options ..', var = val, command = m_frame).place(x=root.winfo_height()/2, y=root.winfo_width()/2)
try: root.mainloop()
except e: showerror('Error!', 'It seems there\'s a problem ..', str(e))
Ofcourse you can also modify the length and the x axis of the main window if you want to be more realistic ..

get previous Entry

I am trying to make a tkinter widget that will remember the previous entry. The problem I am having is the that the button method I made erases the previous entry every time its pressed.
from Tkinter import *
class step1():
def __init__(self):
pass
def getTextbook(self):
temp = str(textbook.get())
textbook.delete(0, END)
x = " "
x += temp
print x
def equal_button(self):
print getTextbook(self)
root = Tk()
root.title("step1")
root.geometry("600x600")
s = step1()
app = Frame(root)
app.grid()
label = Label(app, text = "step1")
label.grid()
textbook = Entry(app, justify=RIGHT)
textbook.grid(row=0, column = 0, columnspan = 3, pady = 5)
textbook2 = Entry(app, justify=RIGHT)
textbook2.grid(row=1, column = 0, columnspan = 3, pady = 5)
button1 = Button(app, text = "Return", command = lambda: s.getTextbook())
button1.grid()
button2 = Button(app, text="Equal")
button2.grid()
root.mainloop()
The variable X in your getTextbook() is being overwritten every time you set it to " ". Try a list instead, and append each entry to the list when the button is pressed:
from Tkinter import *
root = Tk()
textbookList = []
def getTextbook():
textbookList.append(textbook.get())
textbook.delete(0,END)
print textbookList
textbook = Entry(root)
textbook.pack()
btn1 = Button(root, text='Return', command=getTextbook)
btn1.pack()
root.mainloop()

Categories

Resources