cannot change CheckButton variable value - python

I have a little problem with the checkbtn value.
Here is my code:
def select_data():
select_window = Tk()
var_autotrader = IntVar()
check_sites_autotrader = Checkbutton(select_window, text = 'autotrader', variable = var_autotrader)
var_bestcarfinder = IntVar()
var_cardady = IntVar()
var_cars = IntVar()
var_car_gurus = IntVar()
var_iseecars = IntVar()
var_truecar = IntVar()
check_sites_bestcarfinder = Checkbutton(select_window, text = 'bestcarfinder', variable = var_bestcarfinder)
check_sites_cardaddy = Checkbutton(select_window, text = 'cardady', variable = var_cardady)
check_sites_cars = Checkbutton(select_window, text = 'cars.com', variable = var_cars)
check_sites_car_gurus = Checkbutton(select_window, text = 'car gurus', variable = var_car_gurus)
check_sites_iseecars = Checkbutton(select_window, text = 'iseecars', variable = var_iseecars)
check_sites_truecar = Checkbutton(select_window, text = 'truecar', variable = var_truecar)
check_sites_autotrader.grid(row = 0, column = 0, sticky = W)
check_sites_bestcarfinder.grid(row = 1, column = 0, sticky = W)
check_sites_cardaddy.grid(row = 2, column = 0, sticky = W)
check_sites_cars.grid(row = 3, column = 0, sticky = W)
check_sites_car_gurus.grid(row = 4, column = 0, sticky = W)
check_sites_iseecars.grid(row = 5, column = 0, sticky = W)
check_sites_truecar.grid(row = 6, column = 0, sticky = W)
def upload_selected_data():
print(var_autotrader.get())// This one does not give me 1 when check is on
btn = Button(select_window, text = 'go!', command = upload_selected_data)
btn.grid(row = 7, column = 0, sticky = W+E)
The trouble is that my variable is not changing when I check the box
Thank you very much!

Probably you created your "main window" with Tk(). In this case you should create another window with the Toplevel() (Not with Tk()).
It means in your case you should change the select_window = Tk() line to select_window = Toplevel()

Related

how to add an attribute to a class

Just a quick question. I've been researching online and I can't seem to find the answer.
How do you append an element to an object list?
from tkinter import *
class Movie:
def __init__(self, movie, ratings):
self.movie = movie
self.ratings = ratings
class MovieRaterGUI:
def __init__(self, parent):
self.counter = 0
self.index = 0
#variable set up
self.v = StringVar()
self.v.set(" ")
#frames used so you can easily switch between rating frame and summary frame - keeping the search frame
rating_frame = Frame(root)
search_frame = Frame(root)
rating_frame.pack(side="top", expand=True)
search_frame.pack(side="bottom", expand=True)
#rating frame
#list of ratings for movies
self.movies = [
Movie("The Hobbit", ["No Rating", "Forget it", "2", "3", "4", "Must See"]),
Movie("Coraline", ["No Rating", "Forget it", "2", "3", "4", "Must See"]),
Movie("Love, Rosie", ["No Rating", "Forget it", "2", "3", "4", "Must See"])]
#labels
self.movie_label = Label(rating_frame, text = "Please Rate:", borderwidth = 10)
self.current_movie = Label(rating_frame, text = self.movies[self.counter].movie, borderwidth = 10)
self.rating_label = Label(rating_frame, text = "Your rating:", borderwidth = 10)
self.movie_label.grid(row = 0, column = 0, sticky = W)
self.current_movie.grid(row = 0, column = 1, sticky = W)
self.rating_label.grid(row = 1, column = 0, sticky = W)
self.num_choices = (self.movies[self.index].ratings)
for i in range(len(self.num_choices)):
self.option = Radiobutton(rating_frame, variable = self.v, value = i, text = self.num_choices[i], borderwidth = 10)
self.option.grid(row = i+1, column = 1, sticky = W)
next_btn = Button(rating_frame, text = "Next", borderwidth = 10, command = self.next_movie)
previous_btn = Button(rating_frame, text = "Previous", borderwidth = 10, command = self.previous_movie)
next_btn.grid(row = 7, column = 1, sticky = W)
previous_btn.grid(row = 7, column = 0, sticky = W)
#search frame
self.search_label = Label(search_frame, text = "Search for movies with a rating of:", borderwidth = 10)
self.search_label.grid(row=0, column=0, columnspan=len(self.num_choices))
for i in range(len(self.num_choices)):
option = Radiobutton(search_frame, variable = self.v, value = i, text = self.num_choices[i])
option.grid(row = 1, column = i, sticky = W)
show_btn = Button(search_frame, text = "Show", borderwidth = 10)
show_btn.grid(row = 3, column = 0, columnspan = len(self.num_choices))
def next_movie(self):
self.movies.append(self.option)
self.counter +=1
self.current_movie.configure(text = self.movies[self.counter].movie)
def previous_movie(self):
self.movies.remove(self.option)
self.counter -=1
self.current_movie.configure(text = self.movies[self.counter].movie)
if __name__ == "__main__":
root = Tk()
root.title("Movie Ratings")
radiobuttons = MovieRaterGUI(root)
root.mainloop()
I'm trying to add the radio button that the user clicks on to the Movie Object lists for each list in the self.movies list. I am trying to do this when the user clicks the next or previous button.
Thank you!
Try to use setattr
Ex: setattr(object, 'field', value)
You can append the list by .append()
For example
a = [1,2,3,4,5]
a.append(6)
print(a)
Result:
[1,2,3,4,5,6]
Now to insert in different positions
In python first position is [0]
a = [1,2,3,4,5]
a.insert(1,6)
print(a)
Result:
[1,6,2,3,4,5]

Variable not defined issue with a simple GUI program

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

Can't pickle _tkinter.tkapp objects

The problem in that I can't pickle the text in entry fields. I try to make it in the 'record' function.
Error: can't pickle _tkinter.tkapp objects
I want to save data in the file and then read it.
Interface:
#program to record and store your sports results
import shelve
from tkinter import *
class Application(Frame):
'''GUI application ере displays menu for the programm'''
def __init__(self, master):
'''Initialize Frame'''
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
''' Create widgets to get story information and to display story. '''
self.fileDat = 'data'
# label date
Label(self,
text = "date:"
).grid(row = 0, column = 0, columnspan = 2, sticky = W)
# field date
self.date_ent = Entry(self)
self.date_ent.grid(row = 1, column = 1, sticky = W)
# label №
Label(self,
text = "№:"
).grid(row = 0, column = 3, columnspan = 2, sticky = W)
# field №
self.number_ent = Entry(self)
self.number_ent.grid(row = 1, column = 4, sticky = W)
# label km
Label(self,
text = "km:"
).grid(row = 2, column = 0, columnspan = 2, sticky = W)
# field km
self.km_ent = Entry(self)
self.km_ent.grid(row = 3, column = 1, sticky = W)
# label time
Label(self,
text = "time:"
).grid(row = 3, column = 0, columnspan = 2, sticky = W)
# field time
self.time_ent = Entry(self)
self.time_ent.grid(row = 4, column = 1, sticky = W)
# record button
Button(self,
text = "record training",
command = self.record
).grid(row = 5, column = 0, sticky = W)
# show training button
Button(self,
text = "show trining",
command = self.tngDisplay
).grid(row = 5, column = 3, sticky = W)
self.tngField = Text(self, width = 75, height = 10, wrap = WORD)
self.tngField.grid(row = 6, column = 0, columnspan = 4)
def listRecord( self):
date = self.date_ent.get()
km = self.km_ent.get()
time = self.time_ent.get()
tng = [date,km, time]
return tng
def record (self):
tngList = self.listRecord
tngNumber = self.number_ent.get()
datFile = shelve.open(self.fileDat)
datFile[tngNumber] = tngList
#datFile['1'] = tngList
datFile.sync()
datFile.close()
def tngDisplay (self):
tng = ''
self.tngField.delete(0.0, END)
#i=0
datFile = shelve.open(self.fileDat)
for key, item in datFile.items():
tng = str(key) + ': ' + str(item)
# display trainings
self.tngField.insert(0.0, tng)
#i+=1
root = Tk()
root.title('RunForest')
app = Application(root)
root.mainloop()

How do i make a continue button? Python, tkinter

I want to make a button in my widget that when I press it, it proceeds to the next lines of code, and closes the existing widget of where the button is.
from tkinter import *
root = Tk()
Label(root, text = "Childs First name").grid(row = 0, sticky = W)
Label(root, text = "Childs Surname").grid(row = 1, sticky = W)
Label(root, text = "Childs Year of Birth").grid(row = 2, sticky = W)
Label(root, text = "Childs Month of Birth").grid(row = 3, sticky = W)
Label(root, text = "Childs Day of Birth").grid(row = 4, sticky = W)
Fname = Entry(root)
Sname = Entry(root)
x = Entry(root)
y = Entry(root)
z = Entry(root)
Fname.grid(row = 0, column = 1)
Sname.grid(row = 1, column = 1)
x.grid(row = 3, column = 1)
y.grid(row = 2, column = 1)
z.grid(row = 4, column = 1)
button1 = Button(root, text = "Quit", command = root.quit, bg = "Grey", fg = "White", width = 12).grid(row = 5, column = 0, sticky = W)
def save():
Fname_value = Fname.get()
Sname_value = Sname.get()
x_value = x.get()
y_value = y.get()
z_value = z.get()
save()
mainloop()
Sorry for this late answer. To make a 'continue' button:
continue_button = tk.Button(frame,text='continue',command=func)
continue_button.config(width=width_continue_button)
# set the coordinates as you want. here 2,6 for the example
continue_button.grid(row=2,column=6,padx=width_continue_grid)
then you have to write the function 'func' to fulfill your needs.
hope this helps

Why do I get the error: "NameError: global name 'pupiluserinputbox' is not defined"

def pupiluserpass():
global usernames, passwords
usernameinp = pupiluserinputbox.get()
passwordinp = pupilpasswordinputbox.get()
Why do I get the error: NameError: global name 'pupiluserinputbox' is not defined?
The input boxes are in another procedure:
def pupillogin():
ruapupil = Label(app, text = "If you're a pupil log in here:")
ruapupil.grid(row = 1, columnspan = 3, sticky = W)
pupilusername = Label(app, text = "Please enter your Username:")
pupilusername.grid(row = 2, column = 0, sticky = W)
pupiluserinputbox = Entry(app, width = 10)
pupiluserinputbox.grid(row = 2, column = 1, sticky = W)
pupilpassword = Label(app, text = "Please enter your Password:")
pupilpassword.grid(row = 3, column = 0, sticky = W)
pupilpasswordinputbox = Entry(app, width = 10)
pupilpasswordinputbox.grid(row = 3, column = 1, sticky = W)
pupilenter = Button(app, text = "Enter!", command = pupiluserpass)
pupilenter.config(height = 1, width = 8)
pupilenter.grid(row = 4, column = 1, sticky = W)
How can I make this work successfully and not get a NameError?
For a class, you should make the variables that carry those errors attributes to self, i.e. the current instance of that object. This is the de facto way to access these variables in other methods within the class. For example:
def pupiluserpass():
...
usernameinp = self.pupiluserinbox.get()
passwordinp = self.pupilpasswordinputbox.get()
def pupillogin():
...
self.pupiluserinputbox = Entry(app, width = 10)
self.pupiluserinputbox.grid(row = 2, column = 1, sticky = W)
...
self.pupilpasswordinputbox = Entry(app, width = 10)
self.pupilpasswordinputbox.grid(row = 3, column = 1, sticky = W)
You could also do lots of global declarations here instead but it is better to use self.

Categories