this is my code:
self.msg_entry = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
self.msg_entry.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.011)
self.msg_entry.focus()
self.msg_entry.bind("<Return>", self._on_enter_pressed)
def _on_enter_pressed(self, event):
msg = self.msg_entry.get()
self._insert_message(msg, "You")
on hovering on on_enter_pressed function, it's showing function is not accessed and I'm getting the following error:
Traceback (most recent call last):
File "GUI.py", line 91, in <module>
app = ChatApplication()
File "GUI.py", line 15, in __init__
self._setup_main_window()
File "GUI.py", line 76, in _setup_main_window
self.msg_entry.bind("<Return>", self._on_enter_pressed)
AttributeError: 'ChatApplication' object has no attribute '_on_enter_pressed'
(I'm using tkinter in python to implement GUI.)
How can I solve this?
You have wrong indentations - _on_enter_pressed has to be outside __init__
def __init__(self):
# ... code ..
self.msg_entry = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
self.msg_entry.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.011)
self.msg_entry.focus()
self.msg_entry.bind("<Return>", self._on_enter_pressed)
# outside `__init__`
def _on_enter_pressed(self, event):
msg = self.msg_entry.get()
self._insert_message(msg, "You")
Related
from tkinter import *
class ticTactoe:
def __init__(self):
self.root=Tk()
self.root.title("Tic Tac Toe")
self.num=-1
for i in range(3):
for j in range(3):
self.num+=1
exec("btn"+str(self.num)+"=StringVar()")
b = "b"+str(i)+str(j)+"=Button(self.root,padx=68,pady=68,bg='#8cff1a',bd=5,relief=SUNKEN,textvariable='btn'+str(self.num),command=lambda :self.game(self,i,j)).grid(row=i,column=j)"
exec(b)
def game(self,r,c):
Label(self.root,text="X",font="40").grid(row=r,column=c)
def mainloop(self):
self.root.mainloop()
t = ticTactoe()
t.mainloop()
Running
PS F:\TKinter> python 17.py
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\mpank\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "<string>", line 1, in <lambda>
NameError: name 'self' is not defined
The code keeps throwing the AttributeError: '_io.TextIOWrapper' object has no attribute 'tk' and I can't figure out what's causing it, I looked at other posts and nothing has helped me to get an idea of what's going on.
Below is the code that's causing it.
def showhwk(lesson, popup):
lesson = lesson.replace("/","")
popup.withdraw()
show = Tk()
show.title("Homework marks for "+lesson)
show.geometry("+{}+{}".format(positionRight, positionDown))
try:
with open(lesson+".csv", "r") as show:
csvlist = list(csv.reader(show))
for label in range (len(csvlist)):
Label(show, text = "hello").grid(row = label)
except FileNotFoundError:
show.title("Error!")
error = Label(show, text = "Homework file was not found")
error.grid(row = 0)
def goback3(show):
popup.deiconify()
show.withdraw()
returnbut = Button(show, text = "Return", bg = "#79838e", command = lambda: goback3(show)).grid(row = 40, sticky = W+E)
This is the full error:
Traceback (most recent call last):
File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "D:\Desktop\Folders\Python\Coursework\coursework code main.py", line 242, in <lambda>
show = Button(popup, text = "Show homework marks", bg = "green", command = lambda: showhwk(lesson, popup))
File "D:\Desktop\Folders\Python\Coursework\coursework code main.py", line 278, in showhwk
Label(show, text = "hello").grid(row = label)
File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 3143, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2561, in __init__
BaseWidget._setup(self, master, cnf)
File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2530, in _setup
self.tk = master.tk
AttributeError: '_io.TextIOWrapper' object has no attribute 'tk'
You first define show like this:
show = Tk()
Later, you redefine show to be an open file handle with this statement:
with open(lesson+".csv", "r") as show:
Then, you try to use show as the master for a widget here:
Label(show, text = "hello").grid(row = label)
Because show is no longer a widget, it can't be used as the master for another widget. And that is why you get a tkinter error.
I am trying to make a program that shows you what did you do and gives an opportunity to save your deeds and remind them. I did the getting info part and write it to a txt file but taking the info from it and printing in the Text section is what couldn't I do.
This is my code.
from tkinter import *
window = tkinter.Tk()
window.geometry("500x500")
window.title('Hatırlatıcı')
def write():
text = et.get()
file_one = open('jobs.txt', 'a')
file_one.write('{}'.format(text))
file_one.write('\n')
file_one.close()
def read():
file_open = open('jobs.txt', 'r')
if file_open.mode == 'r':
contents = file_open.read()
tarea.insert(contents)
file_open.close()
def al():
write()
read()
lb1 = Label(window, text='What Did You Do?', fg='red', font=("Times", 14,
"bold"), cursor='tcross', justify='center')
et = Entry(font=("Comic Sans MS", 10, "bold"))
b1 = Button(text='Confirm', command=al)
tarea = Text(width='50')
lb1.pack()
et.pack()
b1.pack()
tarea.pack()
et.place(x='30',y='65')
b1.place(x='220',y='65')
tarea.place(x='45',y='150')
window.mainloop()
Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "D:\Anaconda\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "<ipython-input-22-4e2d8f6740e1>", line 22, in al
read()
File "<ipython-input-22-4e2d8f6740e1>", line 17, in read
tarea.insert(contents)
TypeError: insert() missing 1 required positional argument: 'chars'
Exception in Tkinter callback
Traceback (most recent call last):
File "D:\Anaconda\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "<ipython-input-22-4e2d8f6740e1>", line 22, in al
read()
File "<ipython-input-22-4e2d8f6740e1>", line 17, in read
tarea.insert(contents)
TypeError: insert() missing 1 required positional argument: 'chars'
As the insert documentation clearly covers, the method requires two arguments: the index (a Text-form index) and text to insert. For instance
tarea.insert(INSERT, contents)
will insert at the front. See here for more details.
I am trying to create a tkinter label that changes color when clicked to show that it has been visited. I keep getting an attribute error saying that Show_Label has no attribute 'fg'. Please help! Here is the code being used.
class Sheet_Label(Label):
def __init__(self,master,text):
Label.__init__(self,master,text=text,cursor="hand2",font="Times 16 underline",fg="blue")
def button_click(event):
if self.fg =="blue":
self.fg = "purple"
else:
self.fg = "purple"
location = os.getcwd()
file = webbrowser.open_new(location + '\\' + "hello.txt")
self.bind("<Button-1>",func=button_click)
def sheets_view():
sheets_window = Toplevel(window)
hello = modules.Sheet_Label(master=sheets_window,text="Hello")
hello.pack(padx=10,pady=10)
sheets_window.title("Production Sheets")
sheets_window.focus()
x = (screen_width/2) - (500/2)
y = (screen_height/2) - (500/2)
sheets_window.geometry("%dx%d+%d+%d" % (500,500,x,y))
sheets_window.resizable(0,0)
Here is the error message:
Traceback (most recent call last):
File "C:\Users\napaf\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "inventory.py", line 311, in sheets_view
hello = modules.Sheet_Label(master=sheets_window,text="Hello")
File "C:\Users\napaf\Documents\Programming\adco_project\modules.py", line 24, in __init__
self.action = action
NameError: name 'action' is not defined
PS C:\Users\napaf\Documents\Programming\adco_project> python inventory.pyException in Tkinter callback
Traceback (most recent call last):
File "C:\Users\napaf\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\napaf\Documents\Programming\adco_project\modules.py", line 27, in button_click
if self.fg =="blue":
AttributeError: 'Sheet_Label' object has no attribute 'fg'
You aren't initializing self.fg until button_click has been called, but at that point it's too late because you're trying to reference self.fg before setting it.
Also, self.fg is not the same as the fg attribute when you create the widget (eg: Label(..., fg="blue"). If you want to get the value of the widget attribute you should use self.cget('fg') or use the shortcut self['fg']. If you want to set it from within the class itself you should use self.configure(fg="purple").
So I try to separate GUI part from logic part, but I can't call logic function from GUI part. Here's the simplified version of the code:
GUI part
import logic
class Program(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.first_list = QListWidget(self)
self.first_list.setGeometry(15, 35, 140, 42)
add_to_list_button = QPushButton('Add', self)
add_to_list_button.setGeometry(165, 35, 30, 20)
add_to_list_button.clicked.connect(lambda: logic.addToList())
self.second_list = QListWidget(self)
self.second_list.setGeometry(205, 35, 140, 192)
for i in range(30):
self.second_list.addItem(logic.list_one[i][3])
And the logic part
import gui
# list_one and list_two go here
def addToList(self):
for i in range(len(gui.Program.second_list)):
if list_one[i][3] == str(gui.Program.second_list.currentItem().text()):
index = i
list_two.append(list_one[index])
When I run the code and press the Add button I get:
Traceback (most recent call last):
File "/************/gui.py", line 30, in <lambda>
add_to_list_button.clicked.connect(lambda: logic.addToList())
TypeError: addToList() missing 1 required positional argument: 'self'
And when I add self and press the button I get:
add_to_list_button.clicked.connect(lambda: logic.addToList(self))
Traceback (most recent call last):
File "**************/gui.py", line 30, in <lambda>
add_to_list_button.clicked.connect(lambda: logic.addToList(self))
File "**************/logic.py", line 23, in addToList
for i in range(len(gui.Program.second_list)):
AttributeError: type object 'Program' has no attribute 'second_list'
Plus I get lots of other errors like "Cannot find reference 'connect' in 'function', etc.". When the whole code is in one file it works fine. But I have no idea how to separate it right. Sorry for lots of code examples.