I got the error unexpected EOF while parsing when i'm trying to create a conversion program with tkinter. Here is my code:
from tkinter import *
from tkinter.ttk import *
class conversion:
def centi():
def centiMet():
meStr=a.get()
meStrc = eval(meStr)
con=meStrc/100
conS=str(con)
CenMet2=Label(root,text=conS + " Meters",font="CenturyGothic 12 bold").pack()
return
rootCm= Tk()
a = StringVar()
rootCm.geometry("500x300")
rootCm.title("Quick Reference Application - Version 0.1.8 [alpha] ")
label1= Label(rootCm,text="Unit Conversions",font="CenturyGothic 17 bold").pack()
inputCm= Entry(rootCm,textvariable=a).pack()
convButton1= Button(rootCm,text="Convert!",command = centiMet).pack()
root= Tk()
root.geometry("500x300")
root.title("Quick Reference Application - Version 0.1.8 [alpha] ")
label1= Label(root,text="Unit Conversions",font="CenturyGothic 17 bold").pack()
CenMet1= Label(root,text="Please select the type you want!!",font="CenturyGothic 12 bold").pack()
convButton1= Button(root,text="Centimeters to Meters",command = conversion.centi).pack()
The error will show after you clicked the centimeter to meter button and try to convert. It works fine before i tried to make a button to initiate a new window for the cm to meters. Does anyone have any suggestion?
As you noticed, the problem seems to be with the second Tk() element. I am not 100% sure why this is the case, but it seems to work if you use a Toplevel window instead.
class conversion:
def centi():
def centiMet():
meStr = a.get()
con = float(meStr) / 100
Label(rootCm, text="{} Meters".format(con), font="CenturyGothic 12 bold").pack()
rootCm = Toplevel()
rootCm.geometry("500x300")
a = StringVar()
Label(rootCm, text="Unit Conversions", font="CenturyGothic 17 bold").pack()
Entry(rootCm, textvariable=a).pack()
Button(rootCm, text="Convert!", command=centiMet).pack()
Some more pointers:
don't use eval if it can be avoided; use float instead
label = Label(...).pack() will assign the result of pack() to label, not the actual label; also, you do not seem to need those variables anyway
not sure whether this was intentional or not, but you added the result label to the original root, not to the popup-window
If you want to reuse the same label when converting multiple measures, use another StringVar:
class conversion:
def centi():
def centiMet():
b.set("{} Meters".format(float(a.get()) / 100))
...
b = StringVar()
Label(rootCm, textvariable=b, font="CenturyGothic 12 bold").pack()
Related
my problem is "spin" is not defined Pylance(reportUndefinedVariable)
from tkinter import *
from playsound import playsound
#...........................................................
bad=[1,2,3,4,5,6,7,8,9,10]
#...........................................................
def song1():
playsound('g:/song1.wav')
def song2():
playsound('g:/song2.wav')
def rate():
print(spin.get())
#...........................................................
window=Tk()
window.title("login form")
#code
def sign():
if (user.get()=="alireza" and pas.get()=="ramz"):
master=Tk()
master.title("Alireza's App")
Label(master,text="Welcome Alireza",font=("courgette",25),fg="lime").pack()
master.geometry("800x680")
window.destroy()
Label(master,text="").pack()
Label(master,text="this is my first app with python TK i hope you enjoy!",fg="gold",font=("courgette",17)).pack()
Label(master,text="").pack()
btn1=Button(master,text="sound 1",bg="lime",width=15,height=2,command=song1)
btn1.pack()
btn2=Button(master,text="sound2",bg="lime",width=15,height=2,command=song2)
btn2.pack()
Label(master,text="").pack()
Label(master,text="please rate me (from 1 to 10:bad , from 11 to 20:medium , from 21 to 30: good , from 31 to 40:perfect)",fg="red").pack()
spin=Spinbox(master,from_=1,to=4)
spin.pack()
Button(master,text="rate",command=rate).pack()
Label(master,text="").pack()
Button(master,text="quit",bg="red",width=25,height=2,command=master.destroy).pack()
master.mainloop()
else:
lbl.pack()
#.........................................................................................
Label(window,text="username",fg="orange",font=("tahoma",16)).pack()
user=Entry(window)
user.pack()
Label(window,text="password",fg="orange",font=("tahoma",16)).pack()
pas=Entry(window)
pas.pack()
Label(window,text="").pack()
btn=Button(window,text="Enter App",width=15,height=2,command=sign)
btn.pack()
lbl=Label(window,text="username or password is incorrect",fg="red")
#end
window.geometry("300x200")
window.mainloop()
You didn't define Spin in the function. You only did in Line 41 as a local variable so you cant acces it from the "rate" function you created. You could create a Parameter for your function that passes the spin object to solve your problem
So i'm building a project macro tracker using Python Gui Tkinter module.
I'm now trying to extra data from an SQLite database. The data extracted is type Int and I need to convert this to an IntVar so that I can use it as a textvariable in Tkinter's Label.
The Label(textvariable=) method required it be an IntVar in this case.
So just to summarize I need to convert an Int variable to an IntVar variable
Any help would be great,
def display_daily_macros():
daily = sqlite3.connect('daily.db')
data = pandas.read_sql_query("Select * from day", daily)
data_time = data[data['sqltime'] == "2020-09-11"]
all_info = data_time.sum()
protein = all_info['Protein']
print(type(protein))
You could do something like this,
from tkinter import *
root = Tk()
protien = '3' #this could be your value from the database
h = IntVar(value=protien) #declaring an IntVar and setting it to protien
e = Entry(root,textvariable=h) #assigning it to the entry widget
e.pack()
root.mainloop()
Here your defining an IntVar() and then later using the set() method to make it protien.
Hope this is what your looking for.
Cheers
Using python 2.7 and Tkinter.
I am creating four lables in a loop and binding them to . I want the label to return
the name in the label's text.
The problem is that no matter which label I press it returns the name in the last label.
I found this question Python Tkinter: Bind function with labels in for loop with exactly my problem but the solution given does not work for me even if I copied the code exactly.
Please anyone? here is my original code:
# labelbind.py
from Tkinter import *
root = Tk()
root.title('Label choices')
root.geometry('1160x900+650+50')
root.option_readfile('setstyle2.txt')
def lblpress(x):
print 'Label pressed', x
names = ['AMEX', 'CIBC', 'VISA', 'BMO']
col = 150
row = 45
num = 1
for name in names:
bobo = 'lbl' + str(num)
print bobo, name
bobo = Label(root, text = name)
bobo.bind('<ButtonRelease-1>', lambda x = name : lblpress(name))
bobo.place(x = col, y = row)
row += 40
num += 1
root.mainloop()
You don't need to pass anything to the callback. The event object that is given to the callback contains a reference to the widget, and from the widget you can get the text.
For example:
import Tkinter as tk
def lblpress(event):
print 'Label pressed:', event.widget.cget("text")
root = tk.Tk()
names = ['AMEX', 'CIBC', 'VISA', 'BMO']
for name in names:
label = tk.Label(root, text=name)
label.bind("<ButtonRelease-1>", lblpress)
label.pack(side="top")
root.mainloop()
I am trying to take entry from an entry boxes and use them in an equation. Basically it is
Entry_one - Entry_two * entry_three / 12. But I cant seem to figure out how to do this. To make it more clear here is the working python code:
a = int(input('Order Amount. '))
c = int(input('Beams Left. '))
l = int(input('Beam Length. '))
a1 = a-c
a2 = a1*l
a3 = a2/12
print ('The Hourly Count Is: ',a3)
Now here is the code that I'm trying to make do the exact same thing with tkinter:
from tkinter import *
root = Tk()
root.geometry('450x450')
root.title('Hourly Production Count')
def calc_result():
subtract_var = int(total_order_ent.get()) - int(beams_left_ent.get())
beams_left_var = int(subtract_var) * int(length_ent.get())
order_output = int(beams_left_var) / 12
answer_var = order_output.get()
label = Label(root,text = answer_var).pack()
button1 = Button(root,text = 'Enter',command = calc_result,fg='black',bg= 'green').pack()
total_order_ent = Entry(root).pack()
Beams_left_ent = Entry(root).pack()
length_ent = Entry(root).pack()
label_total = Label(root,text = 'Enter Total Order Amount').pack()
label_beams_left = Label(root,text = 'Enter Amount Left To Complete').pack()
root.mainloop()
That's what I have so far. I havn't used any grid placement for the widgets yet since I just want to get the code to work before I work on how it looks but if anyone can help me it would be appreciated. I've searched other questions and have modified other code, tried it as a class and other things and just cant seem to make it work. some errors I'm getting are:
line 23, in <module>
label_length = Label('Enter Beam Length').pack()
Python\Python35\lib\tkinter\__init__.py", line 2109, in _setup
self.tk = master.tk
AttributeError: 'str' object has no attribute 'tk'
Your code doesn't exhibit the error you say it does. Just about the only possible way to get that specific error is if you omit the first three lines of your program after the import, and set root to a string. Even when you do that, you get a slightly different error -- it will complain about the first use of Button rather than Label as in your question.
My guess is, you're not running the exact code you think you are. Regardless, this specific problem is due to the fact you haven't properly created a root window, and you're passing a string as the parent to the other widgets.
Once you solve that problem, you also will need to solve the problem addressed in this question: Tkinter: AttributeError: NoneType object has no attribute get. The short version is, total_order_ent = Entry(root).pack() will set total_order_ent to None, making it impossible to get the value of the widget at a later date.
you could create a variable and retrieve it with the get method in your function:
as explained in the following documentation:
from tkinter import *
root = Tk()
var_01 = StringVar()
enter_01 = Entry(root, textvariable=var_01)
enter_01.pack()
def get_var():
getvar = var_01.get()
print(getvar)
button_01 = Button(root, text='print variable', command=get_var)
button_01.pack()
root.mainloop()
I have had an issue with this piece of code from awhile back, it's part of a GCSE mock and I have currently finished the working code (with text only) but I would like to expand it so that it has a nice GUI. I'm getting some issues with updating my sentence variables within the code. Anyone with any suggestions for me please do explain how I can fix it.
#GCSE TASK WITH GUI
import tkinter
from tkinter import *
from tkinter import ttk
var_sentence = ("default")
window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("Sentence")
window.geometry("400x300")
window.wm_iconbitmap("applicationlogo.ico")
file = open("sentencedata.txt","w")
file = open("sentencedata.txt","r")
def update_sentence():
var_sentence = sentence.get()
def submit():
file.write(sentence)
print ("")
def findword():
messagebox.showinfo("Found!")
print ("Found")
sentencetext = tkinter.Label(window, fg="purple" ,text="Enter Sentence: ")
sentence = tkinter.Entry(window)
sentencebutton = tkinter.Button(text="Submit", fg="red" , command=update_sentence)
findword = tkinter.Label(window, fg="purple" ,text="Enter Word To Find: ")
wordtofind = tkinter.Entry(window)
findwordbutton = tkinter.Button(text="Find!", fg="red" ,command=findword)
usersentence = sentence.get()
usersentence = tkinter.Label(window,text=sentence)
shape = Canvas (bg="grey", cursor="arrow", width="400", height="8")
shape2 = Canvas (bg="grey", cursor="arrow", width="400", height="8")
#Packing & Ordering Moduales
sentencetext.pack()
sentence.pack()
sentencebutton.pack()
shape.pack()
findword.pack()
wordtofind.pack()
findwordbutton.pack()
usersentence.pack()
shape2.pack()
window.mainloop()
If I understand your question right, you want to display the entered text in the usersentence label.
Changing update_sentence() function to what is shown below will archive the desired effect.
def update_sentence():
var_sentence = sentence.get()
usersentence.config(text=var_sentence)
usersentence never gets updated because you only set it once when the program starts this was the problem.