tkinter.entry and NameErrors. - python

I am currently coding a GUI for a palindrome-detector but I have run into some problems. I can launch the program and the GUI appears to be fine. All buttons work except the essential one: Testa Palindrom (translates to Test Palindrome).
Whenever I click that button, I get a NameError: global name 'palindromentry' is not defined.
Below you will find the entire code but first a quick explanation of what it does.
def ordnaText lowers the text and fixes it for the check.
def testap tests whether it is a palindrome or not using a for-loop.
def visaResultat shows the result (this can be see in the label1.config).
My question is: Why am I getting this error? I cannot figure it out for the life of me.
import tkinter
import tkinter.messagebox
def main():
gui()
tkinter.mainloop()
def gui():
main_window = tkinter.Tk()
top_frame = tkinter.Frame()
mid_frame = tkinter.Frame()
bottom_frame = tkinter.Frame()
main_window.title("Palindromdetektor")
main_window.geometry("400x400")
label1 = tkinter.Label(top_frame, text = "Skriv in ett palindrom nedan för att testa det!",
bg = "green", width = 60, height = 6)
button1 = tkinter.Button(mid_frame, text = "Testa palindrom", height = 3, width = 22,
bg = "Purple", command = mainaction)
button2 = tkinter.Button(bottom_frame, text= "Instruktioner", height = 3, width = 22,
bg = "Purple", command = messagebox)
button3 = tkinter.Button(bottom_frame, text ="Spara palindrom", height = 3, width = 22,
bg = "Purple") #command = sparapalindrom)
button4 = tkinter.Button(bottom_frame, text ="Avsluta programmet", height = 3, width = 22,
bg = "Purple", command=main_window.destroy)
palindromentry = tkinter.Entry(mid_frame, width = 67)
palindromentry.pack()
top_frame.pack()
mid_frame.pack()
bottom_frame.pack()
label1.pack()
button1.pack()
button2.pack()
button3.pack()
button4.pack()
def ordnaText(text):
nytext = ("")
fixadText = text.lower()
for i in fixadText:
if i.isalnum():
nytext = (nytext + i)
return nytext
def testap(nytext):
palindrom = True
for i in range (0, len(nytext)):
if (nytext[i]) != (nytext[len(nytext)-i-1]):
palindrom = False
return palindrom
def visaResultat(palindrom):
if palindrom:
label1.config(text="Ja, detta är ett palindrom!", bg="green")
else:
label1.config(text="Nej, detta är inte ett palindrom!", bg="red")
def messagebox():
tkinter.messagebox.showinfo("Hjälp", "Detta är ett program som testar vare sig en text är ett palindrom eller inte.\n \
Skriv in din text i rutan och tryck på Testa Palindrom-knappen så får du se ditt resultat högst upp.\n \
Om du vill avsluta programmet klickar du på knappen som heter Avsluta programmet.\n \
Detta program är kodat av Olof Unge som nås via mail: olofunge#hotmail.com.\n \
Tack för att du använder detta program!")
#def sparapalindrom():
# try:
# if palindrom:
# myfile = open("palindrom.txt", "a")
# myfile.write(text\n)
# myfile.close()
# else:
# label1.config(text="Du kan bara spara godkända palindrom.")
# except IOError:
# label1.config(text="Kunde inte hitta / skapa filen.")
def mainaction():
global text
text = palindromentry.get()
ordnaText(text)
testap(ordnaText(text))
visaResultat(testap(ordnaText(text)))
main()
I would appreciate very much if you could stick to topic and not comment anything else because everything else works fine. Thank you very much!
Best regards.
THIS IS CODED IN PYTHON 3.0

palindromentry is defined in the gui function. As such, it's scope is limited to that single function. When you click the button, the mainaction function is called, but it knows nothing of the gui function's scope.
There are a few options here (in order of my preferences):
Make all of this stuff a class so that you can share the state between function calls
move the definition of mainaction into the gui function (It needs to be defined before the button which does the action ...).
declare palindromentry as global in gui

Related

Python 3: destroy tkinter window after calling lambda function, without quitting the program

So, I want to close the Tkinter window when
w = Button(root, text="Tryck här för att skriva till high score lista", command=lambda :high_score(attempts, computer_word_list_for_display))
w.pack(fill=X)
is pressed.
I have tried
w = Button(root, text="Tryck här för att skriva till high score lista", command=lambda :high_score(attempts, computer_word_list_for_display), root.destroy())
w.pack(fill=X)
but it only gives me an error message. Any ideas?
Here is the function as a whole...
def render_game_after(attempts,computer_word_list_for_display):
root = Tk()
w = Label(root, text="Detta är spelmenyn. Här kommer några alternativ.", bg = "black",fg = "white")
w.pack(fill=X)
w = Button(root, text="Tryck här för att skriva till high score lista", command=lambda :high_score(attempts, computer_word_list_for_display))
w.pack(fill=X)
w = Button(root, text="Klicka här för att se ditt resultat i ett annat fönster",command= lambda:render_highscore(attempts, computer_word_list_for_display))
w.pack(fill=X)
w = Button(root, text="Tryck här för att avsluta spelet", command=lambda: quit())
w.pack(fill=X)
root.mainloop()
Better create function ie.
def on_quit(a, b):
high_score(a, b)
root.destroy()
w = Button(root, text="...", command=lambda:on_quit(attempts, computer_word_list_for_display))
It will be more readable.

How do I add a function result string on the tkinter window?

I am new in python and trying to make a program for converting a given string into a secret code. The string entered by user in the text box is taken as input and converted in secret code (using the encryption module). How do I display the result in the window (I tried using the label but it shows an error.)
from tkinter import *
import encryption as En # Loading Custom libraries
import decryption as De
out_text = None # Out text is the output text of message or the encryption
root = None
font_L1 = ('Verdana', 18, 'bold') # The font of the header label
button1_font = ("Ms sans serif", 8, 'bold')
button2_font = ("Ms sans serif", 8, 'bold')
font_inst = ("Aerial", 8)
my_text = None
input_text = None
text_box = None
resut_l = None
result_2 = None
def b1_action(): # Encryption button
input_text = text_box.get()
if input_text == "":
print("Text field empty")
else:
En.enc_text(input_text) # Message is returned as 'code'
def b2_action():
input_text = text_box.get()
if input_text == "":
print("Text field Empty")
else:
De.dec_text(input_text)
def enc_button(): # Button for rendering encryption
b1 = Button(root, text = "ENCRYPT", font = button1_font, command = b1_action)
b1.configure(bg = 'palegreen3', width = '10', height = '3')
b1.place(x = '120', y = '130')
def dec_button(): # Button for decryption
b2 = Button(root, text = "DECRYPT", font = button2_font, command = b2_action)
b2.configure(bg = 'palegreen3', width = '10', height = '3')
b2.place(x = '340', y = '130')
def main(): #This is the core of GUI
global root
global text_box
root = Tk()
root.geometry("550x350")
root.configure(bg = "MediumPurple1")
win_text = Label(root, text = 'Enter text below and Choose an action:', bg = 'MediumPurple1', font = font_L1)
win_text.place(x = '10', y = '50')
text_box = Entry(root, text = 'Enter the Text', width = 60, bg = 'light blue')
text_box.place(x = '100', y = '100')
inst_text = Label(root, text = instructions, bg = "MediumPurple1", font = font_inst)
inst_text.pack(side = BOTTOM)
enc_button()
dec_button()
root.title('Secret Message.')
root.mainloop()
main()
And here is the encryption module
def enc_text(line):
msg = str(line).replace(' ', '_').lower()
msg_list = list(msg)
all_char = list("abcdefghijklmnopqrstuvwxyzabc_!?#")
for i in range(0, len(msg)):
pos_replaced = all_char.index(str(msg_list[i])) #will give the positon of the word to be replaced in the main list of alphabets
msg_list.insert(i, all_char[pos_replaced + 3]) #will replace the elements one by one
msg_list.pop(i + 1)
i += 1
code = ''.join(msg_list).replace('#', ' ')
print(code)
You can also suggest some improvisations.
Part of the problem is that Entry widgets don't have a text= configuration option, so it's completely ignored in the line:
text_box = Entry(root, text='Enter the Text', width=60, bg='light blue')
The best way to handle the character contents of an Entry is by using its textvariable= option and setting the value of it to be an instance of a tkinter.StringVar, then the getting and setting the value of that object will automatically update the Entry widget on the screen.
Below is your code with changes made to it to do this. Note I commented and changed a few unrelated things to be able to run the code, but tried to indicate the most important ones. Also note I added a return code statement at the very end of the enc_text() function in your custom encryption module.
from tkinter import *
import encryption as En # Loading Custom libraries
#import decryption as De # DON'T HAVE THIS.
out_text = None # Out text is the output text of message or the encryption
root = None
font_L1 = ('Verdana', 18, 'bold') # The font of the header label
button1_font = ("Ms sans serif", 8, 'bold')
button2_font = ("Ms sans serif", 8, 'bold')
font_inst = ("Aerial", 8)
my_text = None
input_text = None
text_var = None # ADDED.
text_box = None
resut_l = None
result_2 = None
# CHANGED TO USE NEW "text_var" variable.
def b1_action(): # Encryption button
input_text = text_var.get()
if input_text == "":
print("Text field empty")
else:
text_var.set(En.enc_text(input_text))
def b2_action():
input_text = text_box.get()
if input_text == "":
print("Text field Empty")
else:
"""De.dec_text(input_text)"""
def enc_button(): # Button for rendering encryption
b1 = Button(root, text="ENCRYPT", font=button1_font, command=b1_action)
b1.configure(bg='palegreen3', width='10', height='3')
b1.place(x='120', y='130')
def dec_button(): # Button for decryption
b2 = Button(root, text="DECRYPT", font=button2_font, command=b2_action)
b2.configure(bg='palegreen3', width='10', height='3')
b2.place(x='340', y='130')
def main(): #This is the core of GUI
global root
global text_box
global text_var # ADDED
root = Tk()
root.geometry("550x350")
root.configure(bg="MediumPurple1")
win_text = Label(root, text='Enter text below and Choose an action:',
bg='MediumPurple1', font=font_L1)
win_text.place(x='10', y='50')
text_var = StringVar() # ADDED
text_var.set('Enter the Text') # ADDED
# CHANGED text='Enter the Text' to textvariable=text_var
text_box = Entry(root, textvariable=text_var, width=60, bg='light blue')
text_box.place(x='100', y='100')
inst_text = Label(root, text="instructions", bg="MediumPurple1",
font=font_inst)
inst_text.pack(side=BOTTOM)
enc_button()
dec_button()
root.title('Secret Message.')
root.mainloop()
main()

tkinter labels dont show

So I got the assignment to make a small Bingo App (Windows btw) after I followed a few webinars on Tkinter GUI and some Googling.
I have made successfull little apps that worked correctly, but this time I try to make it with knowledge I think I have.
Anyway, in that Bingo app, I want 50 labels that represent 50 numbers of the Bingo card, 5 rows of 10 numbers.
I know how to align them, but they need to show up first.
Can you look at my code and assess what I do wrong?
Ignore the many Dutch comments :)
'''
iWMMMM0.
XM#o:..iIMM.
MM. :XC17, YM8
M# v#9. .W# ,M,
#M 7#i ,0$: M0 MM
.M. #7 M#t, ME MQ
MM iM. #$Ci$Q ;M#CCY:.
CM ,M, b#$; v;7IEW#MMM#1
MQ WQ .tE0Q2nCCYc;i,:7#MMi
:M #b . .. .:YCb0U: YMM.
WM E#i .... ,i: ,b#; bMQ,SbW06i
oM MC ... MME9#$Y . .#b SM#b2tob#MM1
Mi #7 ... #M .v iMt ... #X :CoUzt: :MM, nWM#Bc :nQ#$Ui
M: #Y .. M9 MM# b# ... Zb1#Zi. .;Z#Y SMi MM#t;vCMM,CMM0C77bMM8
M, #7 .. #6 Y7 ;Mn ... #QB. ,#b ZM MM .n9U; bMM. ;z2U7 MM
M: #Y ., #9.;tQQv ... ;MQ, :#; Mv MM X$: M; , ;$2. 7#i M8
M: #7 .. #BW1i ..,:Y$Mt$ MX MMtiEM: E#: ZME,.W$c ; c# .M
M: #Y ., ME .. .ZMM8o89 QM. i;U## .Zb7: ,BBYzQ bM# Mi M
Mi #X .. M, iMM#WS :bWQb, ,#M1;IoIX 1#c bMMX iM I#E$CM M, M
.MM #7 ., Mn EM8AEE#: . v$AWQ#$Q#MMIWz, ;$Z$ MMzW2 M# $ZY$C bM CM
MZ ib#i .. ##. ;t $z#. ., CWUWnE$b7: :Y #$c MEYY .MM8 :; vM. M1
iM iMi .., #bWI,..M#i#C .., Mv i#E. UMM2 #BC oC;tMMCES .#M MM
MY E0 ... S#i:Z$MZ .Mv ... M8 7WEz MnZo #obUA: ic.7bEW$#M#C iMM
CMi I#; .. b#; $$ ... ,MQ 7$Zz #zbz #IXW#E69z. 80 ::iAMM;
iM$ .$Qi . :Z$Q0Q#6. ... MQ0 C$b1 MtQ7 YZWW,.c$## MC MMM#b.
MM7 iBWv. .., .M#7$ v$8; vQ0:iCAM: :#bM0 nMU BM
:MM1 .6$Q7: ;MMS:Q7 ##i12EMzEESB# .7:,,2M# MM
,MM#: ,1E$BQbZ6EBMM#; iQQ##B$72n7i.,vo tQQIZQ$WC .#MQ
6MM#o;,,:ivY;i,,iEMM...,,:iC2Q#MMMQ$M$..,i::,;9MMZ
YIEbEAU269086, ;Bb08bAz;:. 7QbEZb8boi
'''
##Basale geimporteerde functies
from tkinter import*
#self=()
#Importeert de randomfucntie
#import random
#Importeert de Python Debugger
#Runnen met pdb.run
#import pdb
#Importeert de PIL Python Image Library
#from PIL import Image, ImageTK
#image = image.open("bestandsnaam.jpg")
#photo ImageTK.PhotoImage(image)
#Een afbeelding op een label
#label = Label(image=photo(als photo de naam van de variable is))
#label.image = photo (bewaren als referentie?<- geen idee nog)
'''
#=# Start van metainfo class/klasse
class MetaBingPy():
def __init__(self):
super(MetaBingPy, self).__init__()
self.parent = parent
self.pack()
MetaBingPy.BingoPyC(self)
##Functie voor random number generator
def BingoPyC:
self.root = Tk()
self.root.title("Python Bingo")
#=#Einde metainfo class
'''
###def random.randint(1,50)
#####of# randrange(1,50)
##GUI voor BingPy, moet root heten. Geen eigen naam, zoals:
##BingPyGUI wat ik had.
root = Tk()
root.wm_title("Bingo Python")
root.wm_maxsize("800","600")
root.wm_minsize("800","600")
#root.wm_grid(baseWidth="800", baseHeight="800")
#root.grid("800x800")
#_tkinter.TclError: wrong # args: should be "wm grid window ?baseWidth baseHeight
#widthInc heightInc?"
##self.title="Bingo Python"
###GUI voor BingPy code, altijd afsluiten met:
###bovenaan
root.mainloop()
'''
#Algemene Python Bingo klasse
class BingoPy
def
'''
#Labels voor alle nummers (50)
label1 = Label(root, text="1jghjgjkhjhg")
label1.grid()
label1.pack()
label2 = Label(root, text="2")
label2.grid()
label2.pack()
label3 = Label(root, text="3")
label3.grid()
label3.pack()
label4 = Label(root, text="4")
label4.grid()
label4.pack()
label5 = Label(root, text="5")
label5.grid()
label5.pack()
label6 = Label(root, text="6")
label6.grid()
label6.pack()
label7 = Label(root, text="7")
label7.grid()
label7.pack()
label8 = Label(root, text="8")
label8.grid()
label8.pack()
label9 = Label(root, text="9")
label9.grid()
label9.pack()
label10 = Label(root, text="10")
label10.grid()
label10.pack()
label11 = Label(root, text="11")
label11.grid()
label11.pack()
label12 = Label(root, text="12")
label12.grid()
label12.pack()
Label13 = Label(root, text="13")
Label13.grid()
Label13.pack()
label14 = Label(root, text="14")
label14.grid()
label14.pack()
label15 = Label(root, text="15")
label15.grid()
label15.pack()
label16 = Label(root, text="16")
label16.grid()
label16.pack()
label7 = Label(root, text="17")
label17.grid()
label17.pack()
label18 = Label(root, text="18")
label18.grid()
label18.pack()
label19 = Label(root, text="19")
label19.grid()
label19.pack()
label20 = Label(root, text="20")
label20.grid()
label20.pack()
label21 = Label(root, text="21")
label21.grid()
label21.pack()
label22 = Label(root, text='22')
label22.grid()
label22.pack()
label23 = Label(root, text="23")
label23.grid()
label23.pack()
label24 = Label(root, text="24")
label24.grid()
label24.pack()
label25 = Label(root, text="25")
label25.grid()
label25.pack()
label26 = Label(root, text="26")
label26.grid()
label26.pack()
label27 = Label(root, text="27")
label27.grid()
label27.pack()
label28.Label(root, text="28")
label28.grid()
label28.pack()
label29 = Label(root, text="29")
label29.grid()
label29.pack()
label30 = Label(root, text="30")
label30.grid()
label30.pack()
label31 = Label(root, text="31")
label31.grid()
label31.pack()
label32 = Label(root, text="32")
label32.grid()
label32.pack()
label33 = Label(root, text="33")
label33.grid()
label33.pack()
label34 = Label(root, text="34")
label34.grid()
label34.pack()
label35 = Label(root, text="35")
label35.grid()
label35.pack()
label36 = Label(root, text="36")
label36.grid()
label36.pack()
label37 = Label(root, text="37")
label37.grid()
label37.pack()
label38 = Label(root, text="38")
label38.grid()
label38.pack()
label39 = Label(root, text="39")
label39.grid()
label39.pack()
label40 = Label(root, text="40")
label40.grid()
label40.pack()
label41 = Label(root, text="41")
label41.grid()
label41.pack()
label42 = Label(root, text="42")
label42.grid()
label42.pack()
label43 = Label(root, text="43")
label43.grid()
label43.pack()
label44 = Label(root, text="44")
label44.grid()
label44.pack()
label45 = Label(root, text="45")
label45.grid()
label45.pack()
label46 = Label(root, text="46")
label46.grid()
label46.pack()
label47 = Label(root, text="47")
label47.grid()
label47.pack()
label48 = Label(root, text="48")
label48.grid()
label48.pack()
label49 = Label(root, text="49")
label49.grid()
label49.pack()
label50 = Label(root, text="50")
label50.grid()
label50.pack()
#Maakt het rood (en als het mogelijk is: doorstrepen) als het getrokken is
#Waarde-return in veld + niet meer zelfde nummer kunnen kiezen
#--------------------------------------------------------------------------
#Knoppen voor afsluiten en nieuw getal
##Afsluiten
#def bingoclose():
# print("Bingo Afsluiten")
'''
bAfsluiten = Button(root,text"Sluit Bingo Af")
bAfsluiten.pack()
'''
'''
{
'title' : ['BingPy'],
'summary' : ['Simple Bingo Python Application with rand.num generator'],
'authors' : ['Thomas']
#'date' : ['2015']
'base_url' : ['http://www.rainydays.eu']
}
'''
'''
Info en weblinks:
https://docs.python.org/3/library/random.html?highlight=random#module-random
http://infohost.nmt.edu/tcc/help/pubs/tkinter/tkinter.pdf (Python 2.7!)
https://wiki.scinet.utoronto.ca/wiki/images/4/41/Pwcgui.pdf
http://stackoverflow.com/questions/3643235/how-to-add-a-margin-to-a-tkinter
-window Margins in Python (padx, pady)
'''
You need to learn about data structures, like list.
You had root.mainloop() early on in the code. That starts a loop. Nothing after that is executed until the window is closed, which means it has to be at the end.
Choose one geometry manager. You can't use both grid() and pack() in the same parent widget, much less on the same child widget.
You had some typos, like label7 = instead of label17 =, and label28.Label instead of label28 = Label. Most of these would never have happened if you had used a list.
Obviously, 50 labels won't fit in a single column in a window of that size. You've got some decisions ahead of you involving window size, label placement, possible scrollbar, and so on.
The resulting code taking into account all these points (except the last) is shown below.
from tkinter import *
root = Tk()
root.wm_title("Bingo Python")
root.wm_maxsize("800","600")
root.wm_minsize("800","600")
labels = [Label(root, text=i) for i in range(1, 51)]
for label in labels:
label.pack()
root.mainloop()

Float is required (in Tkinter)

I have a problem that i still cant solve, specifically involving tkinter.
Eventhough some parts of the code are written in spanish I hope its not a problem.
When trying to calculate the hypotenuse of a triangle with Vel_in_y as the opposing side.
import tkinter
import math
window= tkinter.Tk()
frame = tkinter.Frame(window)
frame.pack()
Velocidad_in =tkinter.IntVar()
Angulo_desp = tkinter.IntVar()
Altura_max = tkinter.IntVar()
Alcan = tkinter.IntVar()
Temp = tkinter.IntVar()
Vel_in_y= tkinter.IntVar()
Vel_in_x= tkinter.IntVar()
var = [Velocidad_in,Angulo_desp ,Altura_max,Alcan,Temp,Vel_in_y,Vel_in_x]
opciones_de_Vel = ['Velocidad Inicial en X','Velocidad Inicial en Y','Modulo de Velocidad']
def Velocidad_Inicial(root):
for (tipo,var) in ((' La Velocidad Inicial en X',Vel_in_x),(' La Velocidad Inicial en Y',Vel_in_y),(' El Modulo de Velocidad',Velocidad_in)):
label = tkinter.Label(frame,text= 'Inserte '+ tipo)
label.pack()
entry= tkinter.Entry(frame,textvariable = var)
entry.pack()
def Angulo_Despegue(root):
label = tkinter.Label(frame,text='Inserte el Angulo de despegue')
label.pack()
entry= tkinter.Entry(frame,textvariable = Angulo_desp)
entry.pack()
def Altura_Maxima(root):
label = tkinter.Label(frame,text='Inserte la Altura Maxima')
label.pack()
entry= tkinter.Entry(frame,textvariable = Altura_max)
entry.pack()
def Alcance(root):
label = tkinter.Label(frame,text='Inserte el Alcance')
label.pack()
entry= tkinter.Entry(frame,textvariable = Alcan)
entry.pack()
def Tiempo(root):
label = tkinter.Label(frame,text='Inserte el Tiempo')
label.pack()
entry= tkinter.Entry(frame,textvariable = Temp)
entry.pack()
def calcular_modulo(root):
modulo = Vel_in_y* math.sin(Angulo_desp)
label = tkinter.Label(frame,textvariable=modulo)
label.pack()
if modulo == 0:
modulo = math.sqrt(Vel_in_x**2+ Vel_in_y**2)
label = tkinter.Label(frame,textvariable=modulo)
label.pack()
button = tkinter.Button(frame,text='respuesta' ,command = lambda: calcular_modulo(window))
button.pack()
menubar = tkinter.Menu(window)
option_menu =tkinter.Menu(menubar)
option_menu.add_command(label= 'Velocidad Inicial',command=lambda:Velocidad_Inicial(window))
option_menu.add_command(label= 'Angulo de Despegue',command=lambda:Angulo_Despegue(window))
option_menu.add_command(label= 'Altura Maxima',command=lambda:Altura_Maxima(window))
option_menu.add_command(label= 'Alcance',command=lambda:Alcance(window))
option_menu.add_command(label= 'Tiempo', command=lambda:Tiempo(window))
menubar.add_cascade(label= 'Tipo de Variable',menu=option_menu)
window.config(menu=menubar)
window.mainloop()
If you spot an error,Ill apreciate all feedback!
BTW when I run this code I get an error saying :
TypeError: a float is required
modulo = Vel_in_y* math.sin(Angulo_desp.get())
math.sin has no idea what to do with an IntVar ... you must get the value
the same applies everywhere else you are trying to access the value of the variables
I don't understand why you use IntVal instead int .
You need to convert IntVal type to int type by use the get function .
Here is your code , it was fixed :
def calcular_modulo(root):
modulo = Vel_in_y.get()* math.sin(Angulo_desp.get())
label = tkinter.Label(frame,textvariable=modulo)
label.pack()
if modulo == 0:
modulo = math.sqrt(Vel_in_x.get()**2+ Vel_in_y.get()**2)
label = tkinter.Label(frame,textvariable=modulo)
label.pack()

Python TkInter Checkbutton not working

Please, help me. This is very strange.
Look at this:
#!/usr/bin/env python
from Tkinter import *
import database
def insertBook():
insertWindow = Tk()
insertWindow.title("Inserisci un nuovo romanzo nel database")
checkvars = []
checkvars.append(IntVar())
checkvars.append(IntVar())
Checkbutton(insertWindow, text = 'male', variable=checkvars[0]).pack()
Checkbutton(insertWindow, text = 'female', variable=checkvars[1]).pack()
Button(insertWindow, text= 'show', command=lambda: show(checkvars)).pack()
insertWindow.mainloop()
def show(checkvars):
print checkvars[0].get()
print checkvars[1].get()
class AppBase:
def __init__(self, parent):
self.quadro1 = Frame(parent)
self.quadro1.pack()
self.welcolmeLabel = Label(self.quadro1, text = "Benvenuto nel database dei romanzi di Lory")
self.welcolmeLabel.pack()
self.insertButton = Button(self.quadro1, command = insertBook);
self.insertButton["borderwidth"] = 1
self.insertButton["text"] = "Inserisci un libro nel database"
self.insertButton["background"] = "pink"
self.insertButton.pack(side = "left")
self.quadro2 = Frame(parent)
self.quadro2.pack()
self.searchButton = Button(self.quadro1);
self.searchButton["borderwidth"] = 1
self.searchButton["text"] = "Ricerca nel database"
self.searchButton["background"] = "blue"
self.searchButton.pack(side = "left")
self.showButton = Button(self.quadro1);
self.showButton["borderwidth"] = 1
self.showButton["text"] = "Mostra i generi di libro"
self.showButton["background"] = "violet"
self.showButton.pack(side = "left")
self.exitButton = Button(self.quadro2, text = "Uscita", borderwidth = 1, background = "red", command = self.quadro1.quit)
self.exitButton.pack(side = RIGHT, pady = 20)
if __name__ == '__main__':
mainFinestra = Tk()
mainFinestra.title('Database di Romanzi')
app = AppBase(mainFinestra)
listvars = []
listvars.append(IntVar())
listvars.append(IntVar())
Checkbutton(mainFinestra, text = 'male', variable=listvars[0]).pack()
Checkbutton(mainFinestra, text = 'female', variable=listvars[1]).pack()
Button(mainFinestra, text= 'show', command=lambda: show(listvars)).pack()
mainFinestra.mainloop()
It seems that checkbuttons variables are set only in the mainFinestra.
If I create checkbuttons in another new window (such as insertWindow), the variables in checkvars are always 0, even if the buttons are checked. Instead if I try to check the checkbutton in the mainFinestra, the function "show" returns 1 if they are checked. What's the difference? Please, this project is important to me.
Thanks
You're doing something that Tkinter isn't designed to do -- you're creating two instances of the class Tk. You should only ever create one instance, and only ever start one event loop.
If you need multiple windows, create instances of Tkinter.Toplevel.

Categories