Alrighty so this is the error I get:
AttributeError: 'DES' object has no attribute 'summary_output'
So this is what I am trying to do.
When I am on this frame, I am creating a text variable that is then sent to a set class.
class upload_csv(Frame):
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master, width=250, height=160, bg='white')
self.upload_csv_btn = Button(
self.frame,
text="Add Data Source",
fg="DodgerBlue4",
font=("Graph Type", 15),
height=1, width=20,
borderwidth=2,
relief="groove",
command=self.upload)
self.upload_csv_btn.place(x=10, y=10)
self.frame.pack()
def upload(self):
global text
self.xvalues = []
self.yvalues = []
self.xyvalues = []
self.header = []
filename = filedialog.askopenfilename()
if len(filename) != 0:
print('Selected:', filename)
with open(filename) as file:
csvreader = csv.reader(file)
self.header.append(next(csvreader))
for row in csvreader:
if len(row) == 3:
self.xvalues.append(int(row[0]))
self.yvalues.append(int(row[1]))
self.xyvalues.append(int(row[2]))
text = (
self.header[0][0]+ ": " + str(self.xvalues).replace('[','').replace(']','') +
"\n\n" + self.header[0][1] + ": " + str(self.yvalues).replace('[','').replace(']','') +
"\n\n" + self.header[0][2] + ": " + str(self.xyvalues).replace('[','').replace(']',''))
elif len(row) == 2:
self.xvalues.append(row[0])
self.yvalues.append(row[1])
text = (
self.header[0][0] + ": " + str(self.xvalues).replace('[','').replace(']','') +
"\n\n" + self.header[0][1] + ": " + str(self.yvalues).replace('[','').replace(']',''))
# -------------------------------------------------------------------------
s = Set(text)
s.set_summary()
#-----------------------------------------------------------------------
Using the upload class, I am sending the variable by calling the set class, and calling the set_summary method. With this set class, I am setting the string as a an object item, that is then send to my DES class. I want this item to be set on a tk textbox element as a summary. I receive the text fine in the DES class, but I get the following error when trying to modify the summary element.
The error I get:
Traceback (most recent call last):
File "C:\Users\***\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Users\***\Documents\Workspace\***\***\view\upload_csv.py", line 115, in upload
s.set_summary()
File "C:\Users\***\Documents\Workspace\***\***\view\Set.py", line 14, in set_summary
s.set_summary_text()
File "C:\Users\***\Documents\Workspace\***\***\view\test.py", line 164, in set_summary_text
print(self.summary_output)
AttributeError: 'DES' object has no attribute 'summary_output'
My set class:
class Set:
def __init__ (self, summary):
self.summary = summary
def set_summary(self):
print(self.summary)
s = DES(self.summary)
s.set_summary_text()
My DES Class:
class DES(Frame):
def __init__(self, summary):
self.summary = summary
def createFrame(self, master):
self.frame = tk.Frame(master, width=750, height=968,bg='white')
self.summary_output = tk.Text(
self.frame,
height=8,
width=78,
bg="gray95",
borderwidth=2,
relief="groove",
font=("Arial", 12))
self.summary_output.configure(state='disabled')
self.summary_output.place(x=20, y=610)
self.frame.pack()
def set_summary_text(self):
print(self.summary)
print(self.summary_output)
self.summary_output.configure(state='normal')
self.summary_output.delete('1.0', END) # Remote all text
self.summary_output.insert('end',self.summary)
self.summary_output.configure(state='disabled') #Make text widget read only
def main():
global root
root = tk.Tk()
# app = DES(root)
# app = DES.createFrame(root)
s = DES("")
s.createFrame(root)
root.mainloop()
if __name__ == '__main__':
main()
Edit:
So after trying the answer I got the following error, all I did was add the suggestion:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\***\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Users\***\Documents\Workspace\\***\\***\view\upload_csv.py", line 115, in upload
s.set_summary()
File "C:\Users\\***\Documents\Workspace\\***\view\Set.py", line 22, in set_summary
s.createFrame(root)
File "C:\Users\\***\Documents\Workspace\\***\view\test.py", line 120, in createFrame
self.canvas.draw() # Create the graph canvas
File "C:\Users\\***\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 11, in draw
self._master.update_idletasks()
AttributeError: 'str' object has no attribute 'update_idletasks'
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\\***\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Users\\***\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\backends\_backend_tk.py", line 235, in filter_destroy
self._master.update_idletasks()
AttributeError: 'str' object has no attribute 'update_idletasks'
So I remove the matplot graph and got this error:
So maybe the graph is interfering? Im not sure, I need the graph.
The summary_output in DES class, will be defined in the
createFrame method.
You first instatiated from the DES class in the Set.set_summary()
method and then called the set_summary_text() method, which it uses
the summary_output. That's not correct, since the summary_output has not been defined, yet.
You should first, call the createFrame() method to define the
summary_output attribute and then call the set_summary_text() to
use summary_output.
Do something like this, in the Set class:
class Set:
def __init__ (self, summary):
self.summary = summary
def set_summary(self):
global root
print(self.summary)
s = DES(self.summary)
s.createFrame(root)
s.set_summary_text()
Or do whatever you think it's best for you, but you should define the summary_output first, and then print or use it.
Related
I have the following two files:
main.py
import tkinter as tk
import hashlib, json
from tkml import element
f = open("users.json", "r")
users = json.loads(f.read())
f.close()
f = open("users.json", "w")
window = tk.Tk()
window.title("Hello wold")
window.geometry("600x800")
pages = {}#initialize this variable
currentPage = ""#initialize this variable
def goTo(pageName):
global pages, currentPage
pages[currentPage].unloads()
pages[pageName].load(window)
currentPage = pageName
pages = {
"SignInOrCreateAccount": element(tk.Frame(),
[
element(tk.Button(text = "sign in", command = lambda : goTo("SignIn")), [], lambda widget, parent : widget.place(parent, anchor = "NW", relx = 0, rely = 0, x = 30, y = 30)),
element(tk.Button(text = "create account", command = lambda : goTo("CreateAccount")), [], lambda widget, parent : widget.place(parent, anchor = "NE", relx = 0, rely = 0, x = 30, y = 30))
], lambda widget, parent: widget.place(parent, relx = 0, rely = 0, relwidth = 1, relheight = 1))
}
currentPage = "SignInOrCreateAccount"
pages[currentPage].loads(window)
def saveUsersChanges():
global f, users
json.dump(users, f)
def attemptSignIn(username, password):
if username in users:
if hashlib.sha256(password.encode()).hexdigest() == users[username]["password"]:
pass # left off here
def onClose():
global f
saveUsersChanges()
f.close()
window.protocol("WM_DELETE_WINDOW", onClose())
tk.mainloop()
and tkml.py
class element:
def __init__(self, widget , children, load, unload = lambda widget: widget.place_forget()):
self.widget = widget # the tk widget
self.load = load # load just this widget using lambda function
self.unload = unload
self.children = children # child widgets
def loads(self, parent): # load this widget and all child widgets
self.load(self.widget, parent)
for child in self.children:
child.loads(self)
def unloads(self): # unloads widget and all child widgets
self.unload(self.widget)
for child in self.children:
child.unloads()
when I attempt to run it I get a very long error:
Traceback (most recent call last):
File "main.py", line 27, in <module>
pages[currentPage].loads(window)
_cnfmerge: fallback due to: 'element' object is not iterable
Traceback (most recent call last):
File "/usr/lib/python3.8/tkinter/__init__.py", line 111, in _cnfmerge
cnf.update(c)
TypeError: 'element' object is not iterable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 27, in <module>
pages[currentPage].loads(None)
File "/home/runner/Phoebe-Hacking-Puzzle/tkml.py", line 10, in loads
child.loads(self)
File "/home/runner/Phoebe-Hacking-Puzzle/tkml.py", line 8, in loads
self.load(self.widget, parent)
_cnfmerge: fallback due to: 'element' object is not iterable
Traceback (most recent call last):
File "/usr/lib/python3.8/tkinter/__init__.py", line 111, in _cnfmerge
cnf.update(c)
TypeError: 'element' object is not iterable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 27, in <module>
pages[currentPage].loads(window)
File "/home/runner/Phoebe-Hacking-Puzzle/tkml.py", line 10, in loads
child.loads(self)
File "/home/runner/Phoebe-Hacking-Puzzle/tkml.py", line 8, in loads
self.load(self.widget, parent)
Traceback (most recent call last):
File "main.py", line 27, in <module>
pages[currentPage].loads(window)
File "/home/runner/Phoebe-Hacking-Puzzle/tkml.py", line 8, in loads
self.load(self.widget, parent)
File "main.py", line 24, in <lambda>
], lambda widget, parent: widget.place(parent, relx = 0, rely = 0, relwidth = 1, relheight = 1))
File "/usr/lib/python3.8/tkinter/__init__.py", line 2439, in place_configure
self.tk.call(
_tkinter.TclError: unknown option "-bd"
I have tried debugging by wading into tkinter's source code and while I have successfully tracked down the line of code that the error comes from, I have no idea where this -bd has come from or what it means. I am new to tkinter, always having used pygame in the past, so there is a good chance I am simply using a function wrong, I would appreciate any help anyone can provide.
PS: I am running my code off repl.it if that makes any difference.
I make a ‘photoplethysmograph’ with Raspberry pi(CM3+) and Maxim sensor(max30102).
I connect between Raspberry pi and Maxim sensor by I2C. I write python program. I want to display ‘photoplethysmograpy’ in canvas.
First, I am success to display that, but noise appear.(program0)
Second, I try to use digital signal processing for removing noise.
sampling frequency: 100Hz
band pass filter :0.1Hz : 10Hz
I write program with band pass filter(progmam1) But, the following error message appear and the program don't move. I want to improve program1. What should I do?
error message:
/usr/lib/python3/dist-packages/scipy/signal/signaltools.py:1344: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
out = out_full[ind]
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "/home/pi/exercize/r210210.py", line 62, in sensor
self.add_point0(self.l0,y0_digital/2000)
File "/home/pi/exercize/r210210.py", line 80, in add_point0
self.c0.coords(line, *coords)
File "/usr/lib/python3.7/tkinter/__init__.py", line 2469, in coords
self.tk.call((self._w, 'coords') + args))]
_tkinter.TclError: bad screen distance "[1.50422694e-04 1.51988575e-02 1.51988575e-02 2.08"
program:
import tkinter as tk
import threading
import time
import max30102
import scipy.signal as signal
class Test():
def __init__(self,master):
self.master = master
self.master.geometry("800x600")
self.frame = tk.Frame(self.master)
self.flag = True
self.c0 = tk.Canvas(self.frame, bg="white", widt=760, height=160)
self.c0.grid(row=0,column=0)
self.c1 = tk.Canvas(self.frame, bg="white", widt=760, height=160)
self.c1.grid(row=1,column=0)
self.buttonB = tk.Button(self.frame, text="start",command=self.measure)
self.buttonB.grid(row=2,column=0)
self.l0 = self.c0.create_line(0,80,0,80,fill="blue")
self.l1 = self.c1.create_line(0,80,0,80,fill="blue")
self.l2 = self.c0.create_line(0,80,0,80,fill="red")
self.frame.grid()
def measure(self):
th0 = threading.Thread(target=self.sensor)
if self.buttonB['text'] == "start":
self.buttonB['text'] = "stop"
self.flag = True
th0.start()
else:
self.buttonB['text'] = "start"
self.flag = False
def sensor(self):
m = max30102.MAX30102()
a,b = signal.buttord([0.002,0.2],[0.001,0.3],3,40)
y0 = []
y1 = []
while self.flag:
red, ir = m.read_fifo()
print('RED'+str(red))
print('IR'+str(ir))
#self.add_point0(self.l0, (red/2000))
#self.add_point1(self.l1, (ir/2000))
y0.append(red)
y1.append(ir)
if len(y0) >= 100:
y0_digital = signal.lfilter(b,a,y0)
y1_digital = signal.lfilter(b,a,y1)
self.add_point0(self.l0,y0_digital/2000)
self.add_point1(self.l1.y1_digital/2000)
self.c0.xview_moveto(1.0)
self.c1.xview_moveto(1.0)
y0.pop(0)
y1.pop(0)
time.sleep(0.01)
m.shutdown()
def add_point0(self, line, y):
coords = self.c0.coords(line)
x = coords[-2] + 1
coords.append(x)
coords.append(y)
coords = coords[-1500:]
self.c0.coords(line, *coords)
self.c0.configure(scrollregion=self.c0.bbox("all"))
def add_point1(self, line, y):
coords = self.c1.coords(line)
x = coords[-2] + 1
coords.append(x)
coords.append(y)
coords = coords[-1600:]
self.c1.coords(line, *coords)
self.c1.configure(scrollregion=self.c1.bbox("all"))
def main():
root = tk.Tk()
app = Test(root)
root.mainloop()
if __name__ == '__main__':
main()
When my program is compiled via pyinstaller I run into this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "tkinter\__init__.py", line 1892, in __call__
File "editSpeakers.py", line 67, in <lambda>
File "editSpeakers.py", line 52, in autoUpdateSpeakers
File "tkinter\__init__.py", line 3043, in get
_tkinter.TclError: invalid command name ".!editspeakers.!canvas.!frame.!entry"
I presume this is a tkinter problem but I have no idea how to fix it and it only shows up when ran via pyinstaller not when ran via the IDE
Code Snippets:
def populate(self):
speakers = main.openSpeakers()
speakersList = sorted(speakers.items())
numRows = len(speakers) + 3
for i in range(numRows):
self.key = tk.Entry(self.frame, width=20, fg="blue", font=("Arial", 16, "bold"))
self.value = tk.Entry(self.frame, width=20, fg="blue", font=("Arial", 16, "bold"))
self.key.grid(row=i, column=0)
self.value.grid(row=i, column=1)
EditSpeakers.entryList.append([self.key, self.value])
try:
self.key.insert(0, speakersList[i][0])
self.value.insert(0, speakersList[i][1])
except IndexError: pass
def autoUpdateSpeakers(self, root):
speakers = dict()
try:
for key, value in EditSpeakers.entryList:
if key.get():
speakers[key.get()] = value.get()
with open("speakers.json", "w") as f:
json.dump(speakers, f, indent=4)
except Exception as e: print(e) ## << Error happening here
finally: root.destroy()
You can find my full code here
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\USER1\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "C:/Users/USER1/AppData/Local/Programs/Python/Python37/newWidget.py", line 54, in clickedEvaluate
txt.insert(END,s[i] +">>>>>>>>>" + Dicesim + "\n")
TypeError: can only concatenate str (not "StringVar") to str
the text above shows the error message
Dicesim=StringVar()
def clickedEvaluate():
if txt1.get()=='':
messagebox.showerror('Empty entry', 'You have not entered the required first text for comparison')
txt1.focus()
else:
combo = Combobox(window)
combo['values']= ('Dice', 'Bigram', 'Trigram', 'Set-Based','NS-Sim')
combo.current(0) #set the selected item
combo.grid(column=0, row=4)
file=open('db_word.txt','r')
s=file.readlines()
txt = ScrolledText(window,width='50',height='10',wrap=WORD)
txt.grid(column=1,row=6)
#txt.pack()
if combo.get()=='Dice':
for i in range(20):
Dicesim.set(dice(txt1.get(),s[i]))
txt.insert(END,s[i] +">>>>>>>>>" + Dicesim + "\n")
txt.yview(END)
The expected result is to display
's[i] +">>>>>>>>>" + Dicesim + "\n"'. this in a line as dice() is performed, the StringVar, Dicesim is not recognised in txt.insert method.
I don't know why this is giving me an attribute error. I want my blah() function to shuffle the cards. I'm calling the builtin function shuffle() from random.
Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1489, in __call__
return self.func(*args)
File "gui1.py", line 105, in blah
shuffle(cards)
AttributeError: Button instance has no __call__ method
Here's the code snippet:
def blah():
global card_count
global path
shuffle(cards)
card_count = 0
path = generate_paths(cards)
print "Cards Shuffled"
shuffle = Button(frame_buttons, text = "SHUFFLE",height = 2, width = 10,command =blah)
shuffle.grid(row = 2 , padx = 40, pady = 40)
shuffle is the name of the function in random. However, it's also the name of the Button. Change the Button's name to something like shuffle_button and you should be fine.