global name "IntVar" not defined - python-3.x

I defined a class and variables inside that class.
I preceded all the variable names with self.varname.
I don't know what is wrong, but I keep getting "global name 'IntVar' not defined" when trying to run the script
This is part of the code:
import tkinter as tk
from tkinter import Frame, Button, Label
import time
import random
class fragal(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid()
self.mymaster = master
self.primes = []
self.cntr1a = 0
self.cntr1b = 0
self.cntr2a = 0
self.cntr2b = 0
self.count = IntVar()
self.count.set(0)
self.time_remaining = IntVar()
self.time_remaining.set(0)
self.gamearray = []
self.equation = StringVar()
self.equation.set("")
Please help! I have several versions of my program and this version was
working until I started changing the main() loop.

IntVar is defined in Tkinter. Because you're importing Tkinter "as tk", you need to prefix IntVar with tk.:
self.count = tk.IntVar()
You also do not need this line: from tkinter import Frame, Button, Label You aren't directly using any of those classes. Plus, you're already importing all of tkinter so you don't need to also import just parts of tkinter.

You have not imported IntVar from tkinter that's why it is undefined. You should impoprt it first by writing this from tkinter import IntVar. Now use your IntVar() and you will not face this problem again.

Related

Tkinter Label class not appearing when used within a class

I am creating a basic GUI with multiple, but similar, label structures. However, when I created a class to help minimize the text, and placed it within a label frame, the label frame does not appear. This only happens when I use the class within a class, and if I use the regular label and label frame classes everything works out well. I'm trying to figure out as to why this is the case.
My code:
main.py
from tkinter import *
def main():
main_window = Tk()
app = First(main_window)
main_window.mainloop()
class GPULabel(Label):
def __init__(self, master, varText):
varText = varText
super().__init__()
self["text"] = varText
self["anchor"] = "w"
self["width"] = 25
class First:
def __init__(self, root):
self.root = root
self.root.title('First Window')
self.myFrame = LabelFrame(self.root, text="frame")
self.myFrame.pack()
label1 = GPULabel(self.myFrame, "label")
lable1.pack()
if __name__ == '__main__'
main()
This opens a window but it is completely empty. However, if I swap to a regular Label(self.myFrame...) then the window pops up correctly. Why is that? And is there a way to make my original method work?

Unable to deselect ttk checkbuttons (initialised by my own class) when another one of my classes creates it

This is a follow-up question from this: Setting ttk checkbutton IntVar to 0, but ttk checkbutton does not deselect. .?
Thanks to the help from #acw1668, I was able to initialise deselected checkbuttons when I created them from __main__. However, when I create my checkbuttons object via a different class, the checkbuttons do not deselect. Here is what I mean:
This is my module Widgets:
import tkinter as tk
from tkinter import ttk
class Checkbuttons():
def __init__(self,parent,list_of_values,column,row,**kwargs):
#Converts list into dictionary
self.values = {}
for value in list_of_values:
self.values[value] = tk.IntVar()
column_counter = column
row_counter = row
for tag in list(self.values):
Checkbutton(parent,tag,self.values[tag],column_counter,row_counter,width=15)
self.values[tag].set(0)
row_counter += 1
class Checkbutton(ttk.Checkbutton):
def __init__(self,parent,text,variable,column,row,search=True,**kwargs):
kwargs['text'] = text
kwargs['variable'] = variable
super().__init__(parent,**kwargs)
self.grid(column=column,row=row)
Now in my main program when I use this class like this:
import Widgets
import tkinter as tk
if __name__ == '__main__':
root = tk.Tk()
my_list = ['e-book epub','e-book PDF','Paperback','Hardcover','Audiobook MP3','Audible','Kindle']
a = Widgets.Checkbuttons(root,my_list,1,1)
root.mainloop()
then it works as expected (all the checkbuttons are deselected). But when I use a class (which generates a frame) to create the checkbuttons, it does not work:
import Widgets
import tkinter as tk
class Frame1(tk.Frame):
def __init__(self,parent,column,row,columnspan=None,rowspan=None,**kwargs):
tk.Frame.__init__(self,parent)
super().__init__(parent,**kwargs)
self.grid(column=column,row=row,columnspan=columnspan,rowspan=rowspan)
my_list = ['e-book epub','e-book PDF','Paperback','Hardcover','Audiobook MP3','Audible','Kindle']
a = Widgets.Checkbuttons(self,my_list,1,1)
class App():
def __init__(self,parent):
a = Frame1(parent,1,4,columnspan=6)
if __name__ == '__main__':
root = tk.Tk()
App(root)
root.mainloop()
I think the problem is in the class which creates the frame, but I do not know how to isolate the problem or how to debug. I am creating instances of all the classes, so I don't think it is getting garbage collected. Will greatly appreciate any help as to why the checkbuttons do not deselect.
Edit: I also tried changing this in my class Checkbuttons:
Checkbutton(parent,tag,self.values[tag],column_counter,row_counter,width=15)
to
a = Checkbutton(parent,tag,self.values[tag],column_counter,row_counter,width=15)
but that also does not help.

Wired that ttk Label textvariable can't be displayed in class properly

I am totally newbie of Python. However i have to use python 3 to do some projects. I am really confused by ttk.Label with textvariable. Below is my codes.
from tkinter import *
from tkinter import ttk
class new_label:
def __init__(self, master):
self.master = master
self.label_var = StringVar()
ttk.Label(self.master, text="iii").grid(row=0, sticky = "w")
self.create_label()
def create_label(self):
self.l1 = ttk.Label(f,
textvariable = self.label_var,
foreground = "red",)
self.l1.grid(row=1)
self.label_var.set("First Label")
print(self.l1.cget("text"))
r=Tk()
r.title("My Label Update")
f=ttk.Frame(r)
f.grid(row=0)
new_label(f)
r.mainloop()
In my codes I add a print and it can print the text well. However the text can't display out and there is no any message of any errors. I do need someone to help for this issue.
Thank you very much in advance.
You aren't keeping a reference so the instance of new_label, so the python garbage collector is collecting it. The ttk widgets are particularly sensitive to the use of garbage-collected StringVar instances.
The simple solution is to keep a reference to your instance of new_label:
x = new_label(f)

python tkinter update content of a label when a file is opened

I'm currently programming a GUI using tkinter and Python 3.
My problem here is i made a Label with which i want to display the path of a file i opened via the askopenfilename() method and this path is not "generated" when i start the program, obviously, so the Label is empty which makes sense but i don't know how to fix it.
I'm gonna put the needed code below (I'm going to cut unnecessary code for this question):
import tkinter as tk
class Graphicaluserinterface(tk.Frame):
def __init__(self,master=None):
super().__init__(master)
self.grid()
self.fileopenname=tk.StringVar()
self.menubar = tk.Menu(self)
self.create_widgets()
def create_widgets(self):
self.inputpathdisplay = tk.Label(self,textvariable=self.fileopenname,bg="white",width=30)
self.inputpathdisplay.grid(row=1,column=8,columnspan=3,sticky = "W")
def fileopening(self):
from tkinter.filedialog import askopenfilename
self.fileopenname = askopenfilename(filetypes = [("binary files","*.bin*"),("all files","*.*")])
root = tk.Tk()
app = Graphicaluserinterface(master=root)
root.config(menu=app.menubar)
app.mainloop()
I read about using update_idletasks(). If this is correct in my case how would i go about implementing it here?
Right now you are doing self.fileopenname = askopenfilename() and this will redefine self.fileopenname as a string instead of a StringVar(). To correct this you need to set the value of StringVar with set().
That said you should also define all your imports at the top of your code instead of in your function.
import tkinter as tk
from tkinter.filedialog import askopenfilename
class Graphicaluserinterface(tk.Frame):
def __init__(self,master=None):
super().__init__(master)
self.grid()
self.fileopenname=tk.StringVar()
self.menubar = tk.Menu(self)
self.inputpathdisplay = tk.Label(self, textvariable=self.fileopenname, bg="white")
self.inputpathdisplay.grid(row=1,column=8,columnspan=3,sticky = "W")
self.fileopening()
def fileopening(self):
self.fileopenname.set(askopenfilename(filetypes = [("binary files","*.bin*"),("all files","*.*")]))
root = tk.Tk()
app = Graphicaluserinterface(master=root)
root.config(menu=app.menubar)
app.mainloop()

python3 tkinter Entry() cannot select text field until I click outside app window once

I've written a very simple app with python3, tkinter, but am seeing some strange behaviour with Entry(). I'm new to tkinter and python.
import os
from tkinter import Tk, Entry, filedialog
class MyGUI:
def __init__(self,master):
self.master = master
self.date_entry = Entry(master)
self.date_entry.pack()
self.date_entry.insert(0,"test")
self.master.mainloop()
root = Tk()
root.directory = os.path.abspath(filedialog.askdirectory())
my_gui = MyGUI(root)
When I run this code, the second to last line is what is causing the following problem:
When I try to edit the "test" text I cannot select it (no cursor or anything). However, if I click once away from the app (e.g. desktop) I can then edit it.
Does anyone know what the problem could be?
I was wondering if it's to do with a new app window being created by the filedialog, but I couldn't find an answer.
Thanks for your replies!
After testing this odd behavior a bit it appear as though as long as you add a button to get the directory the issue goes away.
I find it odd however and I will see if I can find anything that could explain why tkinter is acting like this.
This code should work for you:
import tkinter as tk
from tkinter import filedialog
class MyGUI(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.date_entry = tk.Entry(self)
self.date_entry.pack()
self.date_entry.insert(0, "test")
self.directory = ""
tk.Button(self, text="Get Directory", command=self.get_directory).pack()
def get_directory(self):
self.directory = filedialog.askdirectory()
MyGUI().mainloop()
UPDATE:
I have recently learned that adding update_idletasks() before the filedialog will fix the focus issue.
Updated code:
import os
from tkinter import Tk, Entry, filedialog
class MyGUI:
def __init__(self,master):
self.master = master
self.date_entry = Entry(master)
self.date_entry.pack()
self.date_entry.insert(0,"test")
self.master.mainloop()
root = Tk()
root.update_idletasks() # fix focus issue.
root.directory = os.path.abspath(filedialog.askdirectory())
my_gui = MyGUI(root)

Resources