the entry .get() function is not recognized [duplicate] - python

This question already has answers here:
Tkinter: AttributeError: NoneType object has no attribute <attribute name>
(4 answers)
Closed 4 days ago.
if __name__ == "__main__":
import tkinter as tk
from tkinter import ttk
window = tk.Tk()
def clear():
for btn in toClear.copy():
btn.destroy()
toClear.remove(btn)
def readFilefunction():
clear()
def enter():
path = ent_Filepath.get()
readFile(path)
#window.geometry("250x75+250+75")
ent_Filepath = tk.Entry(window, width=15).pack()
btn_Enter = tk.Button(window,command=enter,text="Enter").pack()#place(x=30,y=20)
def searchFilefunction():
txt_Model = ttk.Entry(window)
txt_Size = ttk.Entry(window)
print('searchFile')
def addRecordfunction():
print('addRecord')
def modQuantityfunction():
print('modQuantity')
functions = {
"readFile": readFilefunction,
"searchFile": searchFilefunction,
"addRecord": addRecordfunction,
"modQuantity": modQuantityfunction
}
toClear = []
title = tk.Label(text= "Please choose a function")
title.pack()
toClear.append(title)
for text, fu1 in functions.items():
frame = tk.Frame(master=window)
frame.pack(side=tk.LEFT)
button = tk.Button(
master=frame,
text=text,
width=10,
height=2,
command=fu1
)
button.pack()
toClear.append(button)
window.mainloop()
the .get function gets the error
Cannot access member "get" for type "None" Pylance(reportGeneralTypeIssues)[Ln 42, Col 33]
Member "get" is unknown
and i'm not sure why
it was working but i changed something but cant remember what sorry. im not sure how to fix it from here. please dont hesitate to ask for any further details

The issue is caused because ent_Filepath is None. If you look at line 15 of the included code, you will see ent_Filepath = tk.Entry(window, width=15).pack(). pack() does not return a value, so you get None. What you should be doing instead is
ent_Filepath = tk.Entry(window, width=15)
ent_Filepath.pack()

Related

how do i add stuff to listbox (tkinter python) [duplicate]

This question already has answers here:
Tkinter: AttributeError: NoneType object has no attribute <attribute name>
(4 answers)
Closed last year.
I'm making a log/chat system in my program (just Tkinter default looks) and i came across a problem where I can't add or change a listbox. Here is what I'm trying to do:
import tkinter
from tkinter import *
from tkinter import messagebox
import random
window = tkinter.Tk()
window.geometry("250x195")
window.title(" ")
window.iconbitmap("icon.ico")
global loglength, log
log = []
loglength = len(log)
inventorylist = []
def sendmessage(event):
chatstring = chatentry.get()
log.append(chatstring)
print(log, loglength)
checknew() #dont worry abt this it works
serverlog = tkinter.Listbox(
width=20,
height=11,
bg="darkgray",
listvariable=log
).place(x=128,y=-2)
I want to add items to the listbox. Here is an image of my program:
When I press enter (the key bound to the function to add the string to the listbox) this happens:
is Listbox like a program u want?
if u want a program that will make u program list in tkinder this is the code :
from tkinter import *
a= Tk()
a.geometry("400x400")
a.title("test")
Lb1 = Listbox(a,bg = "pink", bd = 10, fg = "black",\
font = "Castellar", cursor = "target")
Lb1.insert(1, "lion")
Lb1.insert(2, "tiger")
Lb1.insert(3, "zebra")
Lb1.insert(4, "elephant")
Lb1.insert(5, "deer")
Lb1.insert(6, "fox")
Lb1.insert(7, "Wolf")
Lb1.insert(8, "Gorilla")
Lb1.insert(9, "Jackal")
Lb1.insert(10, "Otter")
Lb1.pack()
a.mainloop()
hope that i helped u.

How do you update labels with grid geometry in Python tkinter? [duplicate]

This question already has answers here:
Tkinter: AttributeError: NoneType object has no attribute <attribute name>
(4 answers)
Closed 2 years ago.
I have a problem with a GUI I created, that includes a label that indicates that the program is working in the background, the real script processes a huge amount of data so I want that indicator to tell the user it is indeed doing something. It worked fine so far like this, displaying "Idle" at script start, "running" while the function runs its course, and "Done" when it's done. (code is only the relevant part):
from tkinter import*
def make_pause_function(sleepytime):
import time
print("Falling asleep")
time.sleep(sleepytime)
print("Awakening")
class MyGUI:
def __init__(self):
self.__mainWindow = Tk()
self.header = StringVar()
self.header.set(3)
self.labelText = 'Idle'
# self.Button2 = Button(text = "Sleep for X seconds!", command = self.run_main_script).grid(row=1,column=0)
# self.Entry2 = Entry(self.__mainWindow, textvariable=self.header, width = 100).grid(row=2,column=0)
# self.Label3 = Label(self.__mainWindow, text = self.labelText).grid(row=3,column=0)
self.Button2 = Button(text = "Sleep for X seconds!", command = self.run_main_script)
self.Entry2 = Entry(self.__mainWindow, textvariable=self.header, width = 100)
self.Label3 = Label(self.__mainWindow, text = self.labelText)
self.Button2.pack()
self.Entry2.pack()
self.Label3.pack()
mainloop()
def run_main_script(self):
self.Label3["text"] = 'running'
self.__mainWindow.update_idletasks()
header=self.header.get()
make_pause_function(int(header))
self.Label3["text"] = 'done'
self.__mainWindow.update_idletasks()
myGUI = MyGUI()
But when the GUI grew because of many options, I switched from pack to grid geometry manager and then the label updating I had gotten working after a lot of trial and error got broken again. The follwing code doesn't work:
from tkinter import*
def make_pause_function(sleepytime):
import time
print("Falling asleep")
time.sleep(sleepytime)
print("Awakening")
class MyGUI:
def __init__(self):
self.__mainWindow = Tk()
self.header = StringVar()
self.header.set(3)
self.labelText = 'Idle'
self.Button2 = Button(text = "Sleep for X seconds!", command = self.run_main_script).grid(row=1,column=0)
self.Entry2 = Entry(self.__mainWindow, textvariable=self.header, width = 100).grid(row=2,column=0)
self.Label3 = Label(self.__mainWindow, text = self.labelText).grid(row=3,column=0)
# self.Button2 = Button(text = "Sleep for X seconds!", command = self.run_main_script)
# self.Entry2 = Entry(self.__mainWindow, textvariable=self.header, width = 100)
# self.Label3 = Label(self.__mainWindow, text = self.labelText)
# self.Button2.pack()
# self.Entry2.pack()
# self.Label3.pack()
mainloop()
def run_main_script(self):
self.Label3["text"] = 'running'
self.__mainWindow.update_idletasks()
header=self.header.get()
make_pause_function(int(header))
self.Label3["text"] = 'done'
self.__mainWindow.update_idletasks()
myGUI = MyGUI()
Seems that update_idletasks doesn't like grid. But I don't like pack for a GUI with lots of buttons and fields. Any way to do what I want with grid packing?
try this:
self.Label3 = Label(self.__mainWindow, text = self.labelText).grid(row=3,column=0)
from that, to this:
self.Label3 = Label(self.__mainWindow, text = self.labelText)
self.Label3.grid(row=3,column=0)
The follwing line causes the error:
self.Label3 = Label(self.__mainWindow, text = self.labelText).grid(row=3,column=0)
grid() is a function that doesn't return anything (None). Because of that, you're saving in variable self.Lable3 nothing. Then, when you run the line self.Label3["text"] = 'running' an error pops up because self.Lable3 is None. In order to solve it, seperate those lines- first save the Label in a variable and then use the grid() function on it:
self.Label3 = Label(self.__mainWindow, text = self.labelText)
self.Label3.grid(row=3,column=0)
By the way, I recommend using place() method instead of grid() because in my opinion it is easier to place objects with it. You can read about it Here

Python Form: Using TKinter --> run script based on checked checkboxes in GUI

I have created the following checkbox popup in Python 3.5 using tkinter (see image) with the following code:
from tkinter import *
class Checkbar(Frame):
def __init__(self, parent=None, picks=[], side=LEFT, anchor=W):
Frame.__init__(self, parent)
self.vars = []
for pick in picks:
var = IntVar()
chk = Checkbutton(self, text=pick, variable=var)
chk.pack(side=side, anchor=anchor, expand=YES)
self.vars.append(var)
def state(self):
return map((lambda var: var.get()), self.vars)
if __name__ == '__main__':
root = Tk()
lng = Checkbar(root, ['DerVar1', 'DerVar2', 'DerVar3', 'DerVar4', 'DerVar5', 'DerVar6', 'DerVar7', 'DerVar8'])
tgl = Checkbar(root, ['DerVar9','DerVar10', 'DerVar11', 'DerVar12', 'DerVar13', 'DerVar14'])
lng.pack(side=TOP, fill=X)
tgl.pack(side=LEFT)
lng.config(relief=GROOVE, bd=2)
def allstates():
print(list(lng.state()), list(tgl.state()))
Button(root, text='Quit', command=root.quit).pack(side=RIGHT)
Button(root, text='Run', command=allstates).pack(side=RIGHT)
root.mainloop()
As you can see I have checked 'DerVar2' and DerVar3'. After I click run I get the following highlighted in yellow.
As you can see a 1 corresponds to a checkbox getting checked.
the variable 'lng' is a checkbar object. I want to say if 'DerVar2' is checked, then print 'test' but can't get it to work.
This is the code I have tried and below is the error I get:
if lng[1] == 1:
print ('test')
TypeError: Can't convert 'int' object to str implicitly
The problem is that your Checkbar class has no __getitem__ method so lng[1] will trigger an error. To do lng[1] == 1 without errors, just add the following method to you rCheckbar class:
def __getitem__(self, key):
return self.vars[key].get()
That way lng[i] will return the value of the i-th IntVar of the Checkbar
You need to explicitly cast to the same types to compare. Try this:
if int(lng[1]) == 1:
print ('test')
or
if lng[1] == str(1):
print ('test')

Allow user to change default text in tkinter entry widget.

I'm writing a python script that requires the user to enter the name of a folder. For most cases, the default will suffice, but I want an entry box to appear that allows the user to over-ride the default. Here's what I have:
from Tkinter import *
import time
def main():
#some stuff
def getFolderName():
master = Tk()
folderName = Entry(master)
folderName.pack()
folderName.insert(END, 'dat' + time.strftime('%m%d%Y'))
folderName.focus_set()
createDirectoryName = folderName.get()
def callback():
global createDirectoryName
createDirectoryName = folderName.get()
return
b = Button(master, text="OK and Close", width=10, command=callback)
b.pack()
mainloop()
return createDirectoryName
getFolderName()
#other stuff happens....
return
if __name__ == '__main__':
main()
I know next to nothing about tkInter and have 2 questions.
Is over-riding the default entry using global createDirectoryName within the callback function the best way to do this?
How can I make the button close the window when you press it.
I've tried
def callback():
global createDirectoryName
createDirectoryName = folderName.get()
master.destroy
but that simply destroys the window upon running the script.
I don't know how experienced are you in Tkinter, but I suggest you use classes.
try:
from tkinter import * #3.x
except:
from Tkinter import * #2.x
class anynamehere(Tk): #you can make the class inherit from Tk directly,
def __init__(self): #__init__ is a special methoed that gets called anytime the class does
Tk.__init__(self) #it has to be called __init__
#further code here e.g.
self.frame = Frame()
self.frame.pack()
self.makeUI()
self.number = 0 # this will work in the class anywhere so you don't need global all the time
def makeUI(self):
#code to make the UI
self.number = 1 # no need for global
#answer to question No.2
Button(frame, command = self.destroy).pack()
anyname = anynamehere() #remember it alredy has Tk
anyname.mainloop()
Also why do you want to override the deafult Entry behavior ?
The solution would be to make another button and bind a command to it like this
self.enteredtext = StringVar()
self.entry = Entry(frame, textvariable = self.enteredtext)
self.entry.pack()
self.button = Button(frame, text = "Submit", command = self.getfolder, #someother options, check tkitner documentation for full list)
self.button.pack()
def getfolder(self): #make the UI in one method, command in other I suggest
text = self.enteredtext.get()
#text now has whats been entered to the entry, do what you need to with it

How to call a function on Tkinter class?(not inside label)

I'm trying to use a function which a placed inside the class of Tkinder but the function(aktodec) can't be found and a get an error. I don't wanna call the def as a command of a button but as a function that will give value to one of my variables
from Tkinter import *
class ADialog:
def __init__(self, parent):
top = self.top = Toplevel(parent)
Label(top, text="Number to convert").pack()
self.numb = Entry(top)
self.numb.pack(padx=15)
Label(top, text="Base of incered number").pack()
self.base = Entry(top)
self.base.pack(padx=15)
Label(top, text="Base you want to be converted").pack()
self.basemet=Entry(top)
self.basemet.pack(padx=15)
b = Button(top, text="OK", command=self.met)
b.pack(pady=5)
def aktodec(self,num,base): #####commands
dec=0
num=num[::-1]
for i in range(len(num)):
s=int(num1[i])*(int(base)**i)
dec=dec+s
def met(self):
num=self.numb=str(self.numb.get())
base=self.base =int(self.base.get())
basemet=self.basemet=int(self.basemet.get())
if base==basemet:
Label(root,text="The number "+self.numb+"is converted to"+self.numb) ##why can't be print??
if base==10:
new=num
else:
new1=self.aktodec(num,base) ####why aktodec doesn't give value to "new"??
Label(root,text="Number is"+str(new))
self.top.destroy()
root = Tk()
def open_dialog():
dial = ADialog(root)
root.wait_window(dial.top)
root.wm_geometry("400x300+20+40")
message=StringVar()
message.set("Complete the form")
Label(root, textvariable=message).pack(padx=30)
root.update()
message.set("Form completed")
Button(root, text="Done", command=root.destroy).pack()
Button(root, text="new", command=open_dialog).pack()
root.update()
root.mainloop()
And also I have a problem whith the label
Label(root,text="The number "+self.numb+"is converted to"+self.numb
which (i don't know why) won't appear to the root even the base=basemet. Help please(it's for a project in this week)!
In Python, a function can't modify some arguments(integers, strings) as perceived by the caller, they are immutable. However, some objects like lists are mutable.
def aktodec(self,num,base):
dec=0
num=num[::-1]
for i in range(len(num)):
s=int(num1[i])*(int(base)**i)
dec=dec+s
return dec
def met(self):
num=self.numb=str(self.numb.get())
base=self.base =int(self.base.get())
basemet=self.basemet=int(self.basemet.get())
new = num
if base==basemet:
Label(root,text="The number "+self.numb+"is converted to"+self.numb).pack()
if base==10:
new=num
else:
new=self.aktodec(num,base)
Label(root,text="Number is"+str(new)).pack()
self.top.destroy()

Categories

Resources