![]() |
Syntax error for "root = Tk()" - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Syntax error for "root = Tk()" (/thread-41490.html) Pages:
1
2
|
Syntax error for "root = Tk()" - dlwaddel - Jan-25-2024 I get a syntax error for "root = Tk()" and can't figure it out. I am running Python 3.12 under Windows 11. Here is the code: >>> from tkinter import* >>> import tkinter.filedialog, os, time, socket, binascii >>> >>> UDP_PORT = 50000 >>> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) >>> >>> # ---------------------------------- >>> # User Interface >>> #------------------------------------ >>> def close(): ... sock.close() ... root.destroy() ... root.quit() ... ... root = Tk() File "<stdin>", line 6 root = Tk() ^^^^ SyntaxError: invalid syntax >>> root.title('Bootloader 2.1') Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'root' is not definedI am not a Python programmer, so have looked around. All instances I found show root = Tk() working just fine. Help will be appreciated! Update! I discovered that copying the program text and pasting it into the interpreter was causing the error. When I opened the file in a Python shell and ran it, the error does not occur. Duh! RE: Syntax error for "root = Tk()" - deanhystad - Jan-25-2024 Why are you typing a program in the python interactive interpreter instead of writing it to a file? Stop doing that. You can use any text editor to create a Python program. Save the file with a .py extension. Run the program by calling python followed by the program filename. You can also install a Python IDE like PyCharm or VSCode that makes it easier to write and run Python programs. This code maked Python thing there is a global variable named "root" that is referenced in the function close(). >>> def close(): ... sock.close() ... root.destroy() ... root.quit()When you enter this like it is indented at the same level as the prior lines, so Python thinks it is also part of function close(). ... root = Tk()This line is in conflict with root.destroy() and root.quit(). By assigning root = Tk() inside the function you are declaring root as a local variable that only exists inside of close(). However lines that use the value of root appear before the assignment. You cannot use a variable before it is assigned, so Python says "SyntaxError". RE: Syntax error for "root = Tk()" - dlwaddel - Jan-25-2024 (Jan-25-2024, 05:41 AM)deanhystad Wrote: Why are you typing a program in the python interactive interpreter instead of writing it to a file? Stop doing that. You can use any text editor to create a Python program. Save the file with a .py extension. Run the program by calling python followed by the program filename. You can also install a Python IDE like PyCharm or VSCode that makes it easier to write and run Python programs. Thanks for the reply. I am not typing into the interpreter. I copied the text from a text editor and pasted it into the interpreter. If I understand correctly, the root=Tk() is in the wrong place. In the original text, the root statement is not indented. Am I correct so far? RE: Syntax error for "root = Tk()" - deanhystad - Jan-25-2024 Quote: I copied the text from a text editor and pasted it into the interpreterWhy are you doing that? RE: Syntax error for "root = Tk()" - dlwaddel - Jan-26-2024 (Jan-25-2024, 03:43 PM)deanhystad Wrote:Quote: I copied the text from a text editor and pasted it into the interpreterWhy are you doing that? Because I did not know any better. I am not a Python user. First try at doing anything, and working with an already written .pyw file that is supposed to talk to a piece of equipment over the network but does not. RE: Syntax error for "root = Tk()" - deanhystad - Jan-26-2024 Can you post the code? What evidence do you have leading you to think it does not work? How do you run the code normally? On windows, a .pyw file is usually run by double clicking on the file. The "w" in the extension tells python to not open a shell window. Remove the "w" and your program will open two windows (cmd or powershell and the tkinter window). As you discovered, you can also run the program by passing the program file name as an argument when starting python (python myprogram.py). RE: Syntax error for "root = Tk()" - dlwaddel - Jan-27-2024 (Jan-26-2024, 06:10 PM)deanhystad Wrote: Can you post the code? What evidence do you have leading you to think it does not work? How do you run the code normally? I remove Python 2 from my computer and reinstalled Python 3.12.1. The converted program will now run from command line and from double-click, but will not talk to the radio. To shorten this story a bit, after you started asking about why I was typing into the interpreter, I looked around a bit more and found the IDLE. That brought up a shell. Using the shell to open the file, rather than copy and paste from Notepad, the program will run, just still will not talk to the radio. The shell does not report any errors until I click the "Test" button to verify connectivity with the radio. When the "Test" button is clicked, the shell reports an error: This will not mean much without the code.I have attempted to attach the file. If that did not work, I can post it in a reply or as an e-mail.[attachment=2727] RE: Syntax error for "root = Tk()" - deanhystad - Jan-27-2024 IDLE is problematic. It gets installed with Python and it isn't a horrible development environment, but there is enough difference between how python runs a program and how IDLE runs a program that I don't use IDLE for anything anymore. Your error message says you are trying to combine bytes and a str. You cannot do that. You could in Python 2.7, but strings are no longer limited to 8bit characters. Programs that used strings to talk to devices now have to use bytes or byte arrays instead of strings. My guess is the code is trying to pad a message with zeros. Don't attach the file, paste the code in your post. RE: Syntax error for "root = Tk()" - dlwaddel - Jan-27-2024 Sounds like I need to convert the strings to bytes. Don't know how, yet. Here is the code" IP1 = '192' IP2 = '168' IP3 = '0' IP4 = '168' from tkinter import* import tkinter.filedialog, os, time, socket, binascii UDP_PORT = 50000 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # ---------------------------------- # User Interface #------------------------------------ def close(): sock.close() root.destroy() root.quit() root=Tk() root.title('Bootloader 2.1') x = str((root.winfo_screenwidth() - root.winfo_reqwidth()) / 3) y = str((root.winfo_screenheight() - root.winfo_reqheight()) / 3) root.geometry('400x300+'+x+'+'+y) root.maxsize(400, 330) root.minsize(400, 330) root.protocol('WM_DELETE_WINDOW', close) #------------------------------------------------------------------- # Main message main_msg = StringVar() main_msg.set(''' Welcome to Bootloader 2.1 for Odyssey TRX. Before using this programm ensure that divice runs in bootloader mode and set current IP address here: ''') main = Label(root, textvariable=main_msg, width=54, height=5, #bd=2, relief=GROOVE, justify=CENTER) main.place(x=8, y=10) # Current IP address selection field ip_addr1 = StringVar() ip_addr2 = StringVar() ip_addr3 = StringVar() ip_addr4 = StringVar() ip_addr1.set(IP1) ip_addr2.set(IP2) ip_addr3.set(IP3) ip_addr4.set(IP4) current_ip_entry1 = Entry(root, width=3, textvariable=ip_addr1) current_ip_entry2 = Entry(root, width=3, textvariable=ip_addr2) current_ip_entry3 = Entry(root, width=3, textvariable=ip_addr3) current_ip_entry4 = Entry(root, width=3, textvariable=ip_addr4) current_ip_entry1.place(x=130, y=62) current_ip_entry2.place(x=160, y=62) current_ip_entry3.place(x=190, y=62) current_ip_entry4.place(x=220, y=62) # Test IP button def test_error_window(msg, color, btn='N', rst='N'): global test_error test_error = Toplevel(root) z = root.winfo_geometry() x = int(z[-7:-4]) + 30 y = int(z[-3:]) + 30 if(color=='green'): abg = 'green' bg = 'pale green' elif(color=='red'): abg = 'red' bg = 'pink' if(rst=='Y'): geo_y = 130 else: geo_y = 100 test_error.geometry('400x300' + '+' + str(x) + '+' + str(y)) test_error.maxsize(400, geo_y) test_error.minsize(400, geo_y) test_error.grab_set() test_error.focus_set() error_msg = StringVar() error_msg.set(msg) error = Label(test_error, textvariable=error_msg, width=54, height=3, relief=GROOVE, justify=CENTER) error.place(x=8, y=10) if(btn=='D'): btn = DISABLED else: btn = NORMAL close_btn = Button(test_error, text="CLOSE", activebackground=abg, bg=bg, bd=1, justify=CENTER, relief=RIDGE, overrelief=SUNKEN, width=53,height=1, state=btn, command=test_error.destroy ) if(rst=='Y'): close_btn.place(x=10, y=97) else: close_btn.place(x=10, y=67) if(rst=='Y'): reset_btn = Button(test_error, text="RESET DEVICE", activebackground=abg, bg=bg, bd=1, justify=CENTER, relief=RIDGE, overrelief=SUNKEN, width=53,height=1, state=btn, command=reset_btn_clicked ) reset_btn.place(x=10, y=68) return None def reset_btn_clicked(): MESSAGE = bytearray(b'RES' + chr(0)*29) # Preparing the message UDP_IP = ip_addr1.get() +'.' + ip_addr2.get() + '.' + ip_addr3.get() + '.' + ip_addr4.get() DEVICE_ADDRESS = (UDP_IP, UDP_PORT) sock.sendto(MESSAGE, DEVICE_ADDRESS)# Sending request test_error.destroy() def test_button_clicked(): ip_1 = ip_addr1.get() ip_2 = ip_addr2.get() ip_3 = ip_addr3.get() ip_4 = ip_addr4.get() if(ip_1.isdigit()!=True or ip_2.isdigit()!=True or ip_3.isdigit()!=True or ip_4.isdigit()!=True or int(ip_1)>255 or int(ip_2)>255 or int(ip_3)>255 or int(ip_4)>255): test_error_window('''The entry is not correct. Please use only digits in the range from 0 to 255 and try again.''', 'red') ip_addr1.set(IP1) ip_addr2.set(IP2) ip_addr3.set(IP3) ip_addr4.set(IP4) return None MESSAGE = bytearray(b'MAC' + chr(0)*29) # Preparing the message UDP_IP = ip_1 +'.' +ip_2 + '.' + ip_3 + '.' + ip_4 DEVICE_ADDRESS = (UDP_IP, UDP_PORT) while(True): # Socket buffer cleaning sock.settimeout(0.1) try: a = sock.recv(4096) except: break reply = None Try = 5 while((reply==None or reply[0:3]!=b'MAC') and Try!=0 ):# Waiting for reply sock.sendto(MESSAGE, DEVICE_ADDRESS)# Sending request sock.settimeout(0.2) try: reply = sock.recv(32) except: None Try -= 1 if(Try==0): test_error_window('''Device was not found. Please check entered IP address and settings of Ethernet connection on your PC.''', 'red') browse_btn['state']=DISABLED filename.set(os.path.abspath(os.curdir)) write_btn['state']=DISABLED ch_ip_btn['state']=DISABLED quit_btn['activebackground'] = 'red' quit_btn['bg'] = 'pink' return None # Reply was received and is corrected MAC1 = binascii.b2a_hex(reply[26]) MAC2 = binascii.b2a_hex(reply[27]) MAC3 = binascii.b2a_hex(reply[28]) MAC4 = binascii.b2a_hex(reply[29]) MAC5 = binascii.b2a_hex(reply[30]) MAC6 = binascii.b2a_hex(reply[31]) test_error_window(('''Device with the specified IP address was found in the current network environment. MAC: '''+MAC1+' '+MAC2+' '+MAC3+' '+MAC4+' '+MAC5+' '+MAC6), 'green', 'N') root.update() self = open('BootLoader_2.1.pyw', 'r')# writing this IP to file self_lines = self.readlines() self.close() self_lines[0] = 'IP1 = ' + "'" + str(ip_addr1.get() + "'\n") self_lines[1] = 'IP2 = ' + "'" + str(ip_addr2.get() + "'\n") self_lines[2] = 'IP3 = ' + "'" + str(ip_addr3.get() + "'\n") self_lines[3] = 'IP4 = ' + "'" + str(ip_addr4.get() + "'\n") try: self = open('BootLoader_2.1.pyw', 'w') except: time.sleep(2) test_error.destroy() test_error_window('''Unable to write the new value to file ! Permissions denied or wrong name of file''', 'red', 'N') root.update() else: self.writelines(self_lines) self.close() browse_btn['state']=NORMAL ch_ip_btn['state']=NORMAL quit_btn['activebackground'] = 'green' quit_btn['bg'] = 'pale green' return None # Test button test_ip_btn = Button(root, text="Test", activebackground='green', bg='grey', bd=1, justify=CENTER, relief=RIDGE, overrelief=SUNKEN, # width=6,height=1, command=test_button_clicked) test_ip_btn.place(x=250, y=60 ) #----------------------------------------------------------------------- # Changing IP ch_ip_msg = StringVar() ch_ip_msg.set('''To change the current IP enter new value and click button. ''') ch_ip = Label(root, textvariable=ch_ip_msg, width=54, height=3, #bd=2, relief=GROOVE, justify=CENTER) ch_ip.place(x=8, y=100) # New IP address selection field new_ip_addr1 = StringVar() new_ip_addr2 = StringVar() new_ip_addr3 = StringVar() new_ip_addr4 = StringVar() new_ip_addr1.set(ip_addr1.get()) new_ip_addr2.set(ip_addr2.get()) new_ip_addr3.set(ip_addr3.get()) new_ip_addr4.set(ip_addr4.get()) new_ip_entry1 = Entry(root, width=3, textvariable=new_ip_addr1) new_ip_entry2 = Entry(root, width=3, textvariable=new_ip_addr2) new_ip_entry3 = Entry(root, width=3, textvariable=new_ip_addr3) new_ip_entry4 = Entry(root, width=3, textvariable=new_ip_addr4) new_ip_entry1.place(x=130, y=122) new_ip_entry2.place(x=160, y=122) new_ip_entry3.place(x=190, y=122) new_ip_entry4.place(x=220, y=122) # Change IP button def write_ip(): ip_1 = new_ip_addr1.get() ip_2 = new_ip_addr2.get() ip_3 = new_ip_addr3.get() ip_4 = new_ip_addr4.get() if(ip_1.isdigit()!=True or ip_2.isdigit()!=True or ip_3.isdigit()!=True or ip_4.isdigit()!=True or int(ip_1)>255 or int(ip_2)>255 or int(ip_3)>255 or int(ip_4)>255): test_error_window('''The entry is not correct. Please use only digits in the range from 0 to 255 and try again.''', 'red') new_ip_addr1.set(ip_addr1.get()) new_ip_addr2.set(ip_addr2.get()) new_ip_addr3.set(ip_addr3.get()) new_ip_addr4.set(ip_addr4.get()) return None global SN if(SN<255): SN += 1 else: SN = 0 MESSAGE = bytearray(b'WIP' + chr(0)*25) # Preparing the message MESSAGE = MESSAGE + chr(int(ip_1)) + chr(int(ip_2)) + chr(int(ip_3)) + chr(int(ip_4)) UDP_IP = ip_addr1.get() +'.' +ip_addr2.get() + '.' + ip_addr3.get() + '.' + ip_addr4.get() DEVICE_ADDRESS = (UDP_IP, UDP_PORT) while(True): # Socket buffer cleaning sock.settimeout(0.1) try: a = sock.recv(4096) except: break reply = None Try = 5 while((reply==None or reply[0:3]!=b'WIP') and Try!=0 ):# Waiting for reply sock.sendto(MESSAGE, DEVICE_ADDRESS)# Sending request sock.settimeout(0.2) try: reply = sock.recv(32) except: None Try -= 1 if(Try==0): test_error_window('''The IP address was not writen sucsesfully ! Please check the connection and try again''', 'red', 'N') browse_btn['state']=DISABLED filename.set(os.path.abspath(os.curdir)) write_btn['state']=DISABLED ch_ip_btn['state']=DISABLED quit_btn['activebackground'] = 'red' quit_btn['bg'] = 'pink' return None # Reply was received and is corrected test_error_window('''The new IP address was writen sucsesfully. Please make changes in Ethernet settings on your PC.''', 'green', 'N') ip_addr1.set(ip_1) # writing new IP to current fields ip_addr2.set(ip_2) ip_addr3.set(ip_3) ip_addr4.set(ip_4) browse_btn['state']=DISABLED filename.set(os.path.abspath(os.curdir)) write_btn['state']=DISABLED ch_ip_btn['state']=DISABLED quit_btn['activebackground'] = 'red' quit_btn['bg'] = 'pink' return None # Write IP button ch_ip_btn = Button(root, text="Write IP", activebackground='green', bg='grey', bd=1, justify=CENTER, relief=RIDGE, overrelief=SUNKEN, # width=6,height=1, command=write_ip, state=DISABLED) ch_ip_btn.place(x=250, y=120 ) #----------------------------------------------------------------------- # Write FW wr_fw_msg = StringVar() wr_fw_msg.set('''For writing FirmWare select needed slot, choose correct file and click button. ''') wr_fw = Label(root, textvariable=wr_fw_msg, width=54, height=8, #bd=2, relief=GROOVE, justify=CENTER) wr_fw.place(x=8, y=160) # Radiobuttons (select slot) rb_state = StringVar() rb_state.set('Slot 1') rbutton0 = Radiobutton(root, text='Slot 0', fg='red', variable=rb_state, value='Slot 0') rbutton0.place(x=80, y=200) rbutton1 = Radiobutton(root, text='Slot 1', variable=rb_state, value='Slot 1') rbutton1.place(x=140, y=200) rbutton2 = Radiobutton(root, text='Slot 2', variable=rb_state, value='Slot 2') rbutton2.place(x=200, y=200) rbutton3 = Radiobutton(root, text='Slot 3', variable=rb_state, value='Slot 3') rbutton3.place(x=260, y=200) # Select file field filename = StringVar() filename.set(os.path.abspath(os.curdir)) file_enter = Entry(root, textvariable=filename, width=61) file_enter.place(x=13, y=230) # Browse file button def browse_clicked(): path = tkinter.filedialog.askopenfilename(#initialdir = "/", title = "Select file",filetypes = [("rbf files","*.rbf")]) if(path == ''): filename.set(os.path.abspath(os.curdir)) else: filename.set(path) if(path[-4:]=='.rbf'): write_btn['state']=NORMAL else: write_btn['state']=DISABLED return None browse_btn = Button(root, text="Browse", activebackground='green', bg='grey', bd=1, justify=CENTER, relief=RIDGE, overrelief=SUNKEN, width=20,height=1, command=browse_clicked, state=DISABLED) browse_btn.place(x=25, y=255) # Write file button def write_clicked(): f = filename.get() f = f.split('/') f = f[-1] slot = rb_state.get() if(slot=='Slot 0' and f[0:10]!='Bootloader'): test_error_window('''Incorrect file for Slot 0 Please select correct Bootloader.rbf file and try again.''', 'red', 'N') filename.set(os.path.abspath(os.curdir)) return None elif(slot!='Slot 0' and f[0:10]=='Bootloader'): test_error_window('''Incorrect file for Slot 1 - 3 Please select correct FirmWare file and try again.''', 'red', 'N') filename.set(os.path.abspath(os.curdir)) return None f = open(filename.get(), 'rb')# open RBF file rbf = f.read() + chr(255)*256 f.close() pages = len(rbf) // 256 if(pages>(32*256)): test_error_window('''This file has too big size for writing to Slot. Please select other file and try again.''', 'red', 'N') filename.set(os.path.abspath(os.curdir)) return None test_error_window('Erasing '+slot+' ...'+'\nPlease wait.', 'green', 'D') root.update() MESSAGE = bytearray(b'ERS' + chr(0)*28 + chr(int(slot[-1])))# Preparing the message UDP_IP = ip_addr1.get() +'.' + ip_addr2.get() + '.' + ip_addr3.get() + '.' + ip_addr4.get() DEVICE_ADDRESS = (UDP_IP, UDP_PORT) while(True): # Socket buffer cleaning sock.settimeout(0.1) try: a = sock.recv(4096) except: break reply = None sock.sendto(MESSAGE, DEVICE_ADDRESS)# Sending request sock.settimeout(10) try: reply = sock.recv(32) except: reply = None if(reply==None): test_error.destroy() test_error_window('''The device did not respond in time ! Please check the connection and try again''', 'red', 'N') browse_btn['state']=DISABLED filename.set(os.path.abspath(os.curdir)) write_btn['state']=DISABLED ch_ip_btn['state']=DISABLED quit_btn['activebackground'] = 'red' quit_btn['bg'] = 'pink' return None test_error.destroy() test_error_window('Writing FirmWare to '+slot+' ...'+'\nPlease wait.', 'green', 'D') root.update() while(True): # Socket buffer cleaning sock.settimeout(0.1) try: a = sock.recv(4096) except: break for i in range(pages): MESSAGE = bytearray(b'WPD' + chr(0)*29) # Preparing the message MESSAGE += rbf[i*256 : i*256+256] reply = None sock.sendto(MESSAGE, DEVICE_ADDRESS)# Sending request sock.settimeout(0.1) try: reply = sock.recv(32+256) except: reply = None if(reply==None or reply!=MESSAGE): test_error.destroy() test_error_window('''The device did not respond in time ! Please check the connection and try again''', 'red', 'N') browse_btn['state']=DISABLED filename.set(os.path.abspath(os.curdir)) write_btn['state']=DISABLED ch_ip_btn['state']=DISABLED quit_btn['activebackground'] = 'red' quit_btn['bg'] = 'pink' return None test_error.destroy() test_error_window('''The writing FirmWare was done sucsesfully.''', 'green', 'N', 'Y') write_btn['state']=DISABLED return None write_btn = Button(root, text="Write FW", activebackground='green', bg='grey', bd=1, justify=CENTER, relief=RIDGE, overrelief=SUNKEN, width=20,height=1, command=write_clicked, state=DISABLED) write_btn.place(x=220, y=255) #------------------------------------------------------------------------ # Quit button quit_btn = Button(root, text="QUIT", activebackground='red', bg='pink', bd=1, justify=CENTER, relief=RIDGE, overrelief=SUNKEN, width=53,height=1, command=close ) quit_btn.place(x=10, y=295) #------------------------------------------------------------------------ root.mainloop()Hope I did that right this time! If you search for "MESSAGE = bytearray" you will find multiple instances of the same problem. RE: Syntax error for "root = Tk()" - deanhystad - Jan-27-2024 This appears to work # This is the test message MESSAGE = b'MAC' + bytes([0]*29) print(MESSAGE, "\n") # This is the reset message MESSAGE = b'RES' + bytes([0]*29) print(MESSAGE, "\n") # This is the change IP messge ip_1 = '192' ip_2 = '168' ip_3 = '0' ip_4 = '168' MESSAGE = b'WIP' + bytes([0]*29) + bytes([int(ip_1), int(ip_2), int(ip_2), int(ip_4)]) print(MESSAGE, "\n") # These messages were in write_clicked() slot = [1, 2, 3] # For testing need a slot list MESSAGE = b'ERS' + bytes([0]*28) + bytes([slot[-1]]) print(MESSAGE, "\n") rbf = bytes(range(256)) # This is read from a file in real program. MESSAGE = b'WPD' + bytes([0]*29) + rbf print(MESSAGE) |