Variable not defined issue with a simple GUI program - python

I'm following the examples in our text and I can't see any issue with the code that would cause this particular issue, it is saying lotnumsred isn't defined and I can't figure out why. Keeps returning NameError: name 'lotnumsred' is not defined.
from tkinter import *
import random
def pickrando():
addnumred = random.randint(1, 35)
lotnumsred.set(addnumred)
window = Tk()
window.title("Powerball")
producebutton = Button(window, text = "Produce a Drawing", command = pickrando())
producebutton.grid(padx=10, pady = 10, row = 0, column = 0, columnspan = 4, sticky = NSEW)
lotnumsred = StringVar()
lotnumswhite = StringVar()
whiteentry = Entry(window, state = "readonly", textvariable = lotnumswhite, width = 10)
whiteentry.grid(padx = 5, pady = 5, row = 1, column = 1, sticky = W)
redentry = Entry(window, state = "readonly", textvariable = lotnumsred, width = 3)
redentry.grid(padx = 5, pady = 5, row = 2, column = 1, sticky = W)
whitelabel = Label(window, text = "White balls:")
whitelabel.grid(padx = 2, pady = 5, row = 1, column = 0, sticky = E)
redlabel = Label(window, text = "Red ball:")
redlabel.grid(padx = 2, pady = 5, row = 2, column = 0, sticky = E)
window.mainloop()
Should be putting a random number in the entry field for the red number, I know that white isn't in the code atm I removed it because it was originally having the same problem and I thought it was something else. So I don't expect the white numbers to work.

from tkinter import *
import random
def pickrando():
addnumred = random.randint(1, 35)
lotnumsred.set(addnumred)
window = Tk()
window.title("Powerball")
producebutton = Button(window, text = "Produce a Drawing", command = pickrando())
producebutton.grid(padx=10, pady = 10, row = 0, column = 0, columnspan = 4, sticky = NSEW)
lotnumsred = StringVar()
lotnumswhite = StringVar()
whiteentry = Entry(window, state = "readonly", textvariable = lotnumswhite, width = 10)
whiteentry.grid(padx = 5, pady = 5, row = 1, column = 1, sticky = W)
redentry = Entry(window, state = "readonly", textvariable = lotnumsred, width = 3)
redentry.grid(padx = 5, pady = 5, row = 2, column = 1, sticky = W)
whitelabel = Label(window, text = "White balls:")
whitelabel.grid(padx = 2, pady = 5, row = 1, column = 0, sticky = E)
redlabel = Label(window, text = "Red ball:")
redlabel.grid(padx = 2, pady = 5, row = 2, column = 0, sticky = E)
window.mainloop()
You are accessing lotnumsred in the function pickrando(). So that means lotnumsred must be defined before you call that function. But pickrando() is supposed to be called whenever a Button is created. But what's actually happening is its being called on line 8
That is why you are getting the error, since pickrando() is being called, before the 10th line where lotnumsred is being definied.
You can change it by doing command = pickrando

Related

Checkbutton is not clickable after adding an image to it

I started working with tkinter recently and I have the following problem, I need to make the check box bigger but that is only possible with adding an image. The problem is that whenever I add an image to a button it becomes unclickable and the image is not displayed, here is my source code (part of a bigger project). My goal is to display some information and let the user decide which option he gets to keep using the check button. Any help is appreciated.
import tkinter as tk
import tkcalendar as tkc
LARGE_FONT = ("HELVETICA", 32, 'bold')
NORMAL_FONT = ("calibri", 18)
class ConstituireDosar(tk.Toplevel):
def __init__(self, controller):
tk.Toplevel.__init__(self)
self.update_idletasks()
# self.dosar = dosar
self.controller = controller
self.minsize(651, 569)
# self.maxsize(651, 569)
frame_titlu = tk.Frame(self)
frame_titlu.grid(row = 0, column = 0)
frame_continut = tk.Frame(self)
frame_continut.grid(row = 1, column = 0, sticky = "w")
frame_acte = tk.Frame(self)
frame_acte.grid(row = 2, column = 0)
titlu = tk.Label(frame_titlu, font = LARGE_FONT, text = "Constituire Dosar")
titlu.grid(row = 0 , column = 0, padx = 10, pady = 15)
data_emiterii = tk.Label(frame_continut, font = NORMAL_FONT,text = "Data emiterii documentului:")
data_emiterii.grid(row = 1, column = 0, padx = 10, pady = 5, sticky = "w")
self.cal = tkc.DateEntry(frame_continut, date_pattern = "DD/MM/YYYY", width = 20)
self.cal.grid(row = 2, column = 0, padx = 10, pady = 5, sticky = "w")
debitori_label = tk.Label(frame_continut, font = NORMAL_FONT, text = "Selecteaza debitorii.")
debitori_label.grid(row = 3, column = 0, padx = 10, pady = 5, sticky = "w")
debitori = []
tip_debitori = []
for i in range(2):
debitori.append("Person %s " % str(i))
tip_debitori.append("Person %s type" % str(i))
for i in range(len(debitori)):
print(debitori[i])
row_i = 4
self.vars_debitori = []
on_image = tk.PhotoImage(width=48, height=24)
off_image = tk.PhotoImage(width=48, height=24)
on_image.put(("green",), to=(0, 0, 23,23))
off_image.put(("red",), to=(24, 0, 47, 23))
for i in range(len(debitori)):
var = tk.IntVar(frame_continut, value = 0)
interior = debitori[i] + " - " + tip_debitori[i]
# Checkbutton(ws, image=switch_off, selectimage=switch_on, onvalue=1, offvalue=0, variable=cb1, indicatoron=False, command=switchState)
checkbuton = tk.Checkbutton (frame_continut, bd = 5, image = off_image, selectimage = on_image, indicatoron = False, onvalue = 1, offvalue = 0, variable = var, state = tk.ACTIVE, command = lambda: self.toggle(var))
checkbuton.grid(row = row_i, column = 0, padx = 20, pady = 5, sticky = "nw")
checkbuton.image = off_image
# checkbuton.select()
self.vars_debitori.append(var)
row_i += 1
self.vars_acte = []
acte = ["Acte de Procedura", "Incheiere de Admitere", "Cerere de Incuviintare", "Instiintare Creditor"]
for i in range(4):
v = tk.IntVar()
check = tk.Checkbutton(frame_acte, font = NORMAL_FONT, text = acte[i], variable = v)
check.grid(row = row_i, column = 0, padx = 10, pady = 5)
check.select()
self.vars_acte.append(v)
row_i += 1
emite_acte = tk.Button(frame_acte, font = NORMAL_FONT, text = "Emite acte.", command = self.emite_acte)
emite_acte.grid(row = row_i, column = 1, padx = 15, pady = 30, ipadx = 70, ipady = 10)
emite_acte.configure(bg = '#218838', fg = '#FFFFFF')
buton_cancel = tk.Button(frame_acte, font = NORMAL_FONT, text = "Cancel", command = lambda: self.destroy())
buton_cancel.grid(row = row_i, column = 0, padx = 15, pady = 30, ipadx = 70, ipady = 10)
buton_cancel.configure(bg = "red", fg = '#FFFFFF')
def emite_acte(self):
print(self.cal.get_date().strftime("%d/%m/%y"))
print(self.winfo_height(), self.winfo_width())
if __name__ == "__main__":
root = tk.Tk()
app = ConstituireDosar(root)
app.protocol("WM_DELETE_WINDOW", root.destroy)
root.withdraw()
root.mainloop()
I tried some options that I saw on the forum, in another file they worked fine but when I tried to implement it in the project itself the checkbutton is still unclickable and it doesn't display the images either. tkinter checkbutton different image I tried to replicate Bryan's answer, but no luck there. Also didn't receive any console error message.
As #furas pointed in the comments above, the problem got fixed with keeping the images as member variables of the class, also the button became clickable after removing the self.toggle(var) command from checkbutton

Python Tkinter: get value from ttk.Combobox

I have the position data in the SQLite DB(employee_position). As well it's fetching the data for the position:
self.employee_position = employee_info[0][8]
However, I'm not able to insert the data. How can I insert the data into the combobox?
It does work for other fields like Entry:
#Entry
self.email_entry.insert(0, self.employee_email)
self.email_entry.config(state = 'disabled')
# Position
self.available = self.employee_position
self.position_lbl = Label(self.centerFrame, text = 'Position:', fg = '#b3b3b3', bg = '#121212')
self.position_lbl.grid(row = 7, column = 0, sticky = W, columnspan = 2, padx = 5)
self.position = ttk.Combobox(self.centerFrame, values=self.available, width = 27)
self.position.config(state = 'disabled')
self.position.grid(row = 7, column = 1, sticky = W, columnspan = 2, pady = 5)
Solution:
# Position
self.available = [self.employee_position]
self.position_lbl = Label(self.centerFrame, text = 'Position:', fg = '#b3b3b3', bg = '#121212')
self.position_lbl.grid(row = 7, column = 0, sticky = W, columnspan = 2, padx = 5)
self.position = ttk.Combobox(self.centerFrame, values=(self.available), width = 27)
self.position.set(self.employee_position)
self.position.config(state = 'disabled')
self.position.grid(row = 7, column = 1, sticky = W, columnspan = 2, pady = 5)

Adding a tkcalendar DateEntry to a tkinter GUI

this my situation. I'm learning how to use python (I just started) to create a GUI with Tkinter. One requirement of my application is to be able to store "DateEntry", while investigating I came across with tkcalendar DateEntry. The problem is that DateEntry is created as a class but my already created window(GUI) is a class as well and I don't know how to combine the class DateEntry into my class client which creates a mainwindow, I think that's beyond my knowledge. I want a DateEntry to be displayed in another toplevel() window when the button "Fecha Check-in" is used. Can anyone explain how to do it?
this is the image
This is the code:
from tkcalendar import DateEntry
from datetime import date
from tkinter import ttk
from tkinter import *
import sqlite3
#year = datetime.date.today().year
#month = datetime.date.today().month
class client:
def __init__(self, window):
self.wind = window
self.wind.title('Start Bits CheckIn-CheckOut')
#self.wind.columnconfigure(0, weight = 1)
#self.wind.rowconfigure(0, weight = 1)
#self.wind.geometry("330x300")
frame_2 = Label(self.wind, text = 'Registro de huéspedes')
frame_2.grid(row = 0, column = 0, pady = 5)
#
frame = LabelFrame(self.wind, text = 'Datos personales', borderwidth=4, relief="raised")
frame.grid(row = 1, column = 0, columnspan = 10, pady = 2, sticky = W + E)
#
# #label ID
L_ID = Label(frame, text = 'Cédula: ').grid(row = 1, column = 0, padx = 1, pady = 1)
self.ID = Entry(frame, width = 25)
self.ID.focus()
self.ID.grid(row = 1, column = 1, columnspan = 2)
#label Nombre
L_name = Label(frame, text = 'Nombres: ').grid(row = 2, column =0, padx = 1, pady = 2)
self.nombre = Entry(frame, width = 25)
self.nombre.grid(row = 2, column = 1, columnspan = 2)
#label last
L_last = Label(frame, text = 'Apellidos: ').grid(row = 3, column = 0, padx = 1, pady = 2)
self.last = Entry(frame, width = 25)
self.last.grid(row = 3, column = 1, columnspan = 2)
#label contact phone
L_phone = Label(frame, text = 'Teléfono: ').grid(row = 4, column = 0, padx = 1, pady = 2)
self.phone = Entry(frame, width = 25)
self.phone.grid(row = 4, column = 1, columnspan = 2)
#label email
L_mail = Label(frame, text = 'Email: ').grid(row = 5, column = 0, padx = 1, pady = 2)
self.mail = Entry(frame, width = 25)
self.mail.grid(row = 5, column = 1, columnspan = 2)
#label CheckIn
L_ChkIN = Label(frame, text = 'Check-In: ').grid(row = 6, column = 0, padx = 1, pady = 5)
ttk.Button(frame, text = 'Fecha Check-In', command = self.fecha_In).grid(row = 6, column = 2)
#label CheckOut
L_ChkOut = Label(frame, text = 'Check-Out').grid(row = 7, column = 0, padx = 1, pady = 5)
#button registrar
ttk.Button(frame, text = 'Registrar' ).grid(row = 2, column = 6, padx = 10)
#button actualizar
ttk.Button(frame, text = 'Actualizar').grid(row = 4, column = 6, padx = 10)
def fecha_In(self):
self.fecha_in = Toplevel()
self.fecha_in.title = 'Fecha Check-In'
if __name__ == '__main__':
window = Tk()
style = ttk.Style(window)
style.theme_use('clam')
alien = PhotoImage(file = "Start Bits.png")
fondo = Label(window, image = alien).grid(row = 8, column = 0)
application = client(window)
window.mainloop()

Python 3.6 tkinter says GROOVE is not defined

The below program was working fine few minutes back. I made a change,ran the code, made a small mistake, Spyder crashed and now it either cannot find Frame or Groove or something else. At the moment it says GROOVE not defined.
Tried writing it in lower case and with quotes. When I do with quotes it says: TclError: bad relief "Groove": must be flat, groove, raised, ridge, solid, or sunken. When I do lower or upper case without quotes says groove not defined.
from RiskFactorConversion import *
from tkinter import ttk, StringVar, Frame, Label, Tk, Entry
mainwindow = Tk()
mainwindow.title("Risk Factor Conversion")
datatype = StringVar()
dataconvention = StringVar()
mdlname = StringVar()
instancevalue = StringVar()
axisvalue = StringVar()
def g():
datatype = e1.get()
dataconvention = e2.get()
mdlname = e3.get()
instancevalue = e4.get()
r1 = rates.srtqualifier(mdlname,datatype,dataconvention,instancevalue)
l5["text"] =r1.makequalifier()
def f():
datatype = e5.get()
dataconvention = e6.get()
axisvalue = e8.get()
fx1 = fx.felixfxvol(datatype,dataconvention,axisvalue)
l11["text"] =fx1.fxvol()
def h():
datatype = en1.get()
dataconvention = en2.get()
fx2 = fx.murexfx(datatype,dataconvention)
la4["text"] =fx2.makequalifier()
#########Felix Frame####################################
frame1 = Frame(bg="white", colormap="new", padx = 10, relief=GROOVE, borderwidth=2)
frame1.grid(row = 0, column = 0)
l0 = Label(frame1, text= "FELIX Rates", pady =5, font = ('Georgia',14,'bold'), bg="white")
l0.grid(row = 0, column = 0,sticky= W )
l1 = Label(frame1, text= "Please provide Data Type:",bg="white", justify = "right",pady =5 )
l1.grid(row = 1, column = 0, sticky= E )
e1 = Entry(frame1,bd = 2, width =50, textvariable = datatype )
e1.grid(row = 1, column = 1)
e1.focus_set()
l2 = Label(frame1,bg="white", text= "Please provide Data Convention:",justify = "right", pady = 5)
l2.grid(row = 2, column = 0,sticky= E)
e2 = Entry(frame1,bd = 2, width =50, textvariable = dataconvention )
e2.grid(row = 2, column = 1)
l3 = Label(frame1,bg="white", text= "Please provide Model Type:", justify = "right",pady = 5)
l3.grid(row = 3, column = 0,sticky= E)
e3 = ttk.Combobox(frame1,width =45, textvariable = mdlname, state='readonly')
e3['values'] = ('IR_SABR','FX_LN','IR_LGM','IR_LMM','IR_SABR_FX_LN_GC','IR_SABR_GC','INFLATION_SABR')
e3.grid(row = 3, column = 1)
l4 = Label(frame1,bg="white", text= "Please provide Instance Name:", justify = "right",pady = 5)
l4.grid(row = 4, column = 0,sticky= E)
e4 = Entry(frame1,bd = 2, width =50, textvariable = instancevalue )
e4.grid(row = 4, column = 1)
bfelix = Button(frame1, text = "Press to get Qualifier Value", pady = 10, command = g)
bfelix.grid(row = 5, column = 0)
l5 = Label(frame1,bg="white", text= "" , justify = "right",pady = 5)
l5.grid(row = 5, column = 1)
################################################################
############FELIX FX############################################
frame2 = Frame(bg="white", colormap="new", padx = 10, relief=GROOVE, borderwidth=2)
frame2.grid(row = 0, column = 1)
l6 = Label(frame2, text= "FELIX FX", pady =5, font = ('Georgia',14,'bold'), bg="white")
l6.grid(row = 0, column = 0,sticky= W )
l7 = Label(frame2, text= "Please provide Data Type:",bg="white", justify = "right",pady =5 )
l7.grid(row = 1, column = 0, sticky= E )
e5 = Entry(frame2,bd = 2, width =50, textvariable = datatype)
e5.grid(row = 1, column = 1)
e5.focus_set()
l8 = Label(frame2,bg="white", text= "Please provide Data Convention:",justify = "right", pady = 5)
l8.grid(row = 2, column = 0,sticky= E)
e6 = Entry(frame2,bd = 2, width =50, textvariable = dataconvention )
e6.grid(row = 2, column = 1)
l10 = Label(frame2,bg="white", text= "Please provide axis 2 value:", justify = "right",pady = 5)
l10.grid(row = 3, column = 0,sticky= E)
e8 = Entry(frame2,bd = 2, width =50, textvariable = axisvalue )
e8.grid(row = 3, column = 1)
bfelixfx = Button(frame2, text = "Press to get Qualifier Value", pady = 10, command = f)
bfelixfx.grid(row = 4, column = 0)
l11 = Label(frame2,bg="white", text= "" , justify = "right",pady = 5)
l11.grid(row = 4, column = 1)
#####################################################################
############MUREX FX############################################
frame3 = Frame(bg="white", colormap="new", padx = 10, relief=GROOVE, borderwidth=2)
frame3.grid(row = 1, column = 1)
la = Label(frame3, text= "Murex FX", pady =5, font = ('Georgia',14,'bold'), bg="white")
la.grid(row = 0, column = 0,sticky= W )
la1 = Label(frame3, text= "Please provide Risk Factor Type:",bg="white", justify = "right",pady =5 )
la1.grid(row = 1, column = 0, sticky= E )
en1 = ttk.Combobox(frame3, width =45, textvariable = mdlname, state='readonly')
en1['values'] =('FX ATM VOLATILITY','FX BUTTERFLY 10D','FX BUTTERFLY 25D','FX RISK REVERSAL 10D','FX RISK REVERSAL 25D')
en1.grid(row = 1, column = 1)
en1.focus_set()
la2 = Label(frame3,bg="white", text= "Please provide Currency Pair:",justify = "right", pady = 5)
la2.grid(row = 2, column = 0,sticky= E)
en2 = Entry(frame3,bd = 2, width =50, textvariable = dataconvention )
en2.grid(row = 2, column = 1)
bmurexfx = Button(frame3, text = "Press to get Qualifier Value", pady = 10, command = h)
bmurexfx.grid(row = 4, column = 0)
la4 = Label(frame3,bg="white", text= "" , justify = "right",pady = 5)
la4.grid(row = 4, column = 1)
#####################################################################
mainwindow.mainloop()
Groove is a constant defined in Tkinter and since you are only importing specfic functions from Tkinter that doesn't include Groove, you need to add GROOVE to it or add
import tkinter as tk
and then set relief=tk.GROOVE

tkinter window is blank after executing code

I'm starting to code with Python and on my first application I have reached a brick wall. Any help on why this code is not displaying the widgets will be greatly appreciated!
import tkinter
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
class ImprintPlusApp:
def _init_(self, master):
self.frame_header = ttk.Frame(master)
self.frame_header.pack()
ttk.Label(self.header_frame, text = "Bienvenidos a Imprint Plus Manager")
self.frame_crearorden = ttk.Frame(master)
self.frame_crearorden.pack()
ttk.Label(self.frame_crearorden, text = "Nombre").grid(row = 0, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Email").grid(row = 2, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Numero Cel/Tel").grid(row = 4, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Información Adicional").grid(row = 6, column = 0, padx = 5)
self.entry_name = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_email = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_numtc = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_addinf = Text(self.frame_crearorden, width = 50, height = 10)
self.entry_name.grid(row = 0, column = 1, padx = 5)
self.entry_email.grid(row = 2, column = 1, padx = 5)
self.entry_numtc.grid(row = 4, column = 1, padx = 5)
self.entry_addinf.grid(row = 7, column = 0, columnspan = 2, padx = 5)
ttk.Button(self.frame_crearorden, text = "Submit", command = self.submit).grid(row = 8, columnspan = 1, padx = 5)
ttk.Button(self.frame_crearorden, text = "Clear", command = self.clear).grid(row = 8, columnspan = 0, padx = 5)
def submit(self):
print ("Nombre: {}".format(self.entry_name.get()))
print ("Email: {}".format(self.entry_name.get()))
print ("Num Cel/Tel: {}".format(self.entry_name.get()))
print ("Información Adicional: {}".format(self.entry_name.get(1.0, "end")))
self.clear()
messagebox.showinfo(tite = "Orden #", message = "Orden Guardada")
def clear(self):
self.entry_name.delete(0, "end")
self.entry_email.delete(0, "end")
self.entry_numtc.delete(0, "end")
self.entry_addinf.delete(1.0, "end")
def main():
root = Tk()
app = ImprintPlusApp()
root.mainloop()
if __name__ == '__main__':
main()
Everytime I launch the code I get a blank tkinter window.
This had a few problems.
You had an _init_ method, not an __init__ method, so the created object wasn't being initialized.
You have to send the root tkinter object to the application, with app = ImprintPlusApp(root).
You had a self.header_frame once instead of self.frame_header.
You had a columnspan = 0 (which is invalid) instead of columnspan = 1 (which doesn't really need to be specified).
I've made the above changes in the code below. It may still need debugging, as I don't know exactly what design you had in mind.
import tkinter
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
class ImprintPlusApp:
def __init__(self, master):
self.frame_header = ttk.Frame(master)
self.frame_header.pack()
ttk.Label(self.frame_header, text = "Bienvenidos a Imprint Plus Manager")
self.frame_crearorden = ttk.Frame(master)
self.frame_crearorden.pack()
ttk.Label(self.frame_crearorden, text = "Nombre").grid(row = 0, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Email").grid(row = 2, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Numero Cel/Tel").grid(row = 4, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Información Adicional").grid(row = 6, column = 0, padx = 5)
self.entry_name = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_email = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_numtc = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_addinf = Text(self.frame_crearorden, width = 50, height = 10)
self.entry_name.grid(row = 0, column = 1, padx = 5)
self.entry_email.grid(row = 2, column = 1, padx = 5)
self.entry_numtc.grid(row = 4, column = 1, padx = 5)
self.entry_addinf.grid(row = 7, column = 0, columnspan = 2, padx = 5)
ttk.Button(self.frame_crearorden, text = "Submit", command = self.submit).grid(row = 8, columnspan = 1, padx = 5)
ttk.Button(self.frame_crearorden, text = "Clear", command = self.clear).grid(row = 8, columnspan = 1, padx = 5)
def submit(self):
print ("Nombre: {}".format(self.entry_name.get()))
print ("Email: {}".format(self.entry_name.get()))
print ("Num Cel/Tel: {}".format(self.entry_name.get()))
print ("Información Adicional: {}".format(self.entry_name.get(1.0, "end")))
self.clear()
messagebox.showinfo(tite = "Orden #", message = "Orden Guardada")
def clear(self):
self.entry_name.delete(0, "end")
self.entry_email.delete(0, "end")
self.entry_numtc.delete(0, "end")
self.entry_addinf.delete(1.0, "end")
def main():
root = Tk()
app = ImprintPlusApp(root)
root.mainloop()
if __name__ == '__main__':
main()

Categories