After a restart my script won't work anymore.
It worked before. Windows popping up, things needed to typed in and there was a result which I was happy with (like v0.9-alpha-happy). Now it yells at me.
import random
import tkinter as tk
from tkinter import simpledialog
from tkinter import messagebox
from tkinter import *
alleSpieler = []
team_eins = []
first_window = tk.Tk
first_window.withdraw()
def main():
global alleSpieler, i, x
i = 1
x = simpledialog.askinteger("Spieleranzahl", "Anzahl der Spieler: ")
if x % 2 == 0:
while i < x + 1:
spieler = simpledialog.askstring("Spielername", "Gib Spielername {} ein: ".format(i))
alleSpieler.append(spieler)
i = i + 1
else:
messagebox.showinfo("Nope", "Bitte gib eine gerade Anzahl von Spielern ein!")
main()
def sec():
j = 1
while j <= len(alleSpieler):
random_name = random.choice(alleSpieler)
team_eins.append(random_name)
alleSpieler.remove(random_name)
j = j + 1
def teams():
root = Tk()
t = Text(root)
for n in team_eins:
t.insert(END,"Team 1: " + n + "\n")
for n in alleSpieler:
t.insert(END,"Team 2: " + n + "\n")
t.pack()
root.mainloop()
main()
sec()
team1()
And the error(s):
/Users/benediktrautenberg/PycharmProjects/TeamGenerator/venv/bin/python /Users/benediktrautenberg/PycharmProjects/TeamGenerator/Generator.py
Traceback (most recent call last):
File "/Users/benediktrautenberg/PycharmProjects/TeamGenerator/Generator.py", line 48, in <module>
main()
File "/Users/benediktrautenberg/PycharmProjects/TeamGenerator/Generator.py", line 17, in main
x = simpledialog.askinteger("Spieleranzahl", "Anzahl der Spieler: ")
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/simpledialog.py", line 343, in askinteger
d = _QueryInteger(title, prompt, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/simpledialog.py", line 271, in __init__
Dialog.__init__(self, parent, title)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/simpledialog.py", line 137, in __init__
if parent.winfo_viewable():
AttributeError: 'NoneType' object has no attribute 'winfo_viewable'
Process finished with exit code 1
All I did to solve this error was:
first_window = Tk()
first_window.withdraw()
You forgot the () near Tk, so your not actually instantiating it properly.
Related
I want to code a short programme. My idea was to code a login window. Then the next window opens and then I should be able to encrypt a text I wrote into a ScrolledText. The whole encryption should be done with the ceasar principal. I combined my code(at the bottom) with this one:
def caesar(text, schluessel):
geheim = ''
for i in text:
number = ord(i) + schluessel #122 = 119+3
if number > 122:
number -= 26
elif number == 32 + schluessel: #whitespace
number = 32
letter = chr(number)
geheim += letter
print(geheim)
I recieved this error message:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:/Users/pc/PycharmProjects/test_22_11_22/main.py", line 77, in caesar
for i in encryptiontextentry:
File "C:\Program Files\Python38\lib\tkinter\__init__.py", line 1643, in cget
return self.tk.call(self._w, 'cget', '-' + key)
TypeError: can only concatenate str (not "int") to str
This is my code:
from tkinter import *
from tkinter.scrolledtext import ScrolledText
class Login:
def __init__(self):
self.user ={'1':'1'}
self.loginwindow = Tk()
self.loginwindow.geometry("500x300")
self.loginwindow.resizable(width= False, height= False)
self.loginlabel = Label(text="Login",font= ("arial",50))
self.loginausgabe = Label(self.loginwindow)
self.loginusernamelabel = Label(self.loginwindow, text="Username",font= ("arial",12))
self.loginusernameentry = Entry(self.loginwindow,font= ("arial",12))
self.loginpasswordlabel = Label(self.loginwindow,text="Password",font= ("arial",12))
self.loginpasswordentry = Entry(self.loginwindow,font= ("arial",12), show="*")
self.loginbtn = Button(self.loginwindow,text="login",width= 38, command=self.login)
self.loginlabel.place(x="140",y="0")
self.loginausgabe.place(x="140",y="140")
self.loginusernamelabel.place(x="140",y ="80")
self.loginusernameentry.place(x="230",y="80")
self.loginpasswordlabel.place(x="140",y ="100")
self.loginpasswordentry.place(x="230",y="100")
self.loginbtn.place(x="140",y="120")
self.loginwindow.mainloop()
def login(self):
loginusernameentry = self.loginusernameentry.get()
if loginusernameentry in self.user.keys():
if self.loginpasswordentry.get() == self.user[loginusernameentry]:
self.loginausgabe.config(text="Welcome!")
self.encryption()
else: self.loginausgabe.config(text="Invalid password!")
else: self.loginausgabe.config(text="Unknown User!")
self.loginusernameentry.config(text="")
self.loginusernameentry.config(text="")
def encryption(self):
self.loginwindow.destroy()
self.encryptionwindow = Tk()
self.encryptionwindow.geometry("1000x600")
self.encryptionwindow.resizable(width= False, height= False)
self.encryptiontextlabel = Label(self.encryptionwindow,text="encryption text",font= ("arial",12))
self.encryptiontextentry = ScrolledText(self.encryptionwindow)
self.decryptiontextlabel = Label(self.encryptionwindow,text="dencryption text",font= ("arial",12))
self.decryptiontextentry = ScrolledText(self.encryptionwindow)
self.encryptionbtn = Button(self.encryptionwindow,text="encrypt",command=self.caesar)
self.caesarkeyencryption = Entry(self.encryptionwindow,width="2")
self.decryptionbtn = Button(self.encryptionwindow,text="decrypt",command=self.caesar)
self.caesarkeydecryption = Entry(self.encryptionwindow,width="2")
self.decryptiontextlabel.place(x="120", y="310")
self.decryptiontextentry.place(x="120", y="330", width="800",height="200")
self.encryptiontextlabel.place(x="120", y="40")
self.encryptiontextentry.place(x="120", y="60", width="800",height="200")
self.encryptionbtn.place(x="120",y="260")
self.caesarkeyencryption.place(x="170",y="264")
self.decryptionbtn.place(x="120",y="530")
self.caesarkeydecryption.place(x="170",y="534")
self.encryptionwindow.mainloop()
** def caesar(self):
caesarkeyencryption = int(self.caesarkeyencryption.get())
encryptiontextentry = self.encryptiontextentry
print(caesarkeyencryption)
encryptiontextresult = ''
for i in encryptiontextentry:
number = ord(i) + caesarkeyencryption
if number > 122:
number -= 26
elif number == 32 + caesarkeyencryption: #whitespace
number = 32
letter = chr(number)
encryptiontextresult += letter
print(encryptiontextresult)
**
l = Login()
I utilised and modified the code that is shown below, from https://www.instructables.com/Monitor-and-Record-Temperature-With-Bluetooth-LE-a/
The problem I run into is that the device seems to be blocking me from accessing it's values, although I am unsure of this.
Here is my code:
from bluepy.btle import Scanner, DefaultDelegate
import time
import struct
SENSOR_ADDRESS = [""ec:fe:4e:12:b8:72""]
class DecodeErrorException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class ScanDelegate(DefaultDelegate):
def __init__(self):
DefaultDelegate.__init__(self)
def handleDiscovery(self, dev, isNewDev, isNewData):
if isNewDev:
print("Discovered device", dev.addr)
elif isNewData:
print("Received new data from", dev.addr)
scanner = Scanner().withDelegate(ScanDelegate())
ManuDataHex = []
ReadLoop = True
try:
while (ReadLoop):
devices = scanner.scan(2.0)
ManuData = ""
for dev in devices:
entry = 0
TempData = 0
for saddr in SENSOR_ADDRESS:
entry += 1
if (dev.addr == saddr):
CurrentDevAddr = saddr
for (adtype, desc, value) in dev.getScanData():
if (desc == "Manufacturer"):
ManuData = value
if (ManuData == ""):
print("No data received, end decoding")
continue
print(ManuData)
for i, j in zip(ManuData[::2], ManuData[1::2]):
ManuDataHex.append(int(i+j, 16))
if ((ManuDataHex[0] == 0x85) and (ManuDataHex[1] == 0x00)):
print("Header byte 0x0085 found")
else:
print("Header byte 0x0085 not found, decoding stop")
continue
idx = 7
print("TotalLen: " + str(len(ManuDataHex)))
while idx < len(ManuDataHex):
if (ManuDataHex[idx] == 0x43):
idx += 1
TempData = ManuDataHex[idx]
TempData += ManuDataHex[idx+1] * 0x100
TempData = TempData * 0.0625
idx += 2
else:
idx += 1
print("Device Address: " + CurrentDevAddr)
print("Temp Data: " + str(TempData))
ReadLoop = False
except DecodeErrorException:
pass
The exception is as follows:
Traceback (most recent call last):
File "/home/pi/Desktop/lameteo/print.py", line 31, in
devices = scanner.scan(2.0)
File "/usr/local/lib/python3.7/dist-packages/bluepy/btle.py", line 852, in scan
self.start(passive=passive)
File "/usr/local/lib/python3.7/dist-packages/bluepy/btle.py", line 790, in start
self._mgmtCmd("le on")
File "/usr/local/lib/python3.7/dist-packages/bluepy/btle.py", line 312, in _mgmtCmd
raise BTLEManagementError("Failed to execute management command '%s'" % (cmd), rsp)
bluepy.btle.BTLEManagementError: Failed to execute management command 'le on' (code: 20, error: > Permission Denied)
If you have any expertise in this area I would greatly appreciate your help.
use sudo infront when you call the script in your terminal
I build des encryption_gui. I got error:
TypeError: Object type <class 'str'> cannot be passed to C code
from Crypto.Cipher import DES
from tkinter import *
gui = Tk()
def click_btn(event):
print("btn click")
def pad(text):
n = len(text) % 8
return text + (b' ' * n)
t_p = textfield_e.get()
text1 = t_p
t_key = textfield_key.get()
key = t_key
des = DES.new(key, DES.MODE_ECB)
padded_text = pad(text1)
encrypted_text = des.encrypt(padded_text)
textfield_d.insert(0,encrypted_text)
def pad(text):
n = len(text) % 8
return text + (b' ' * n)
gui.geometry('540x600')
gui.title('PyCryptor')
title_h = Label(gui,text='Encryption',font=('kanit',22))
title_h.pack(pady=10)
plant_box = Label(gui,text='Plain Text')
plant_box.pack()
textfield_e = Entry(gui,justify=CENTER,font=('font',15),relief='solid')
textfield_e.pack(side=TOP,fill=X,padx=30,pady=10,ipady=10)
key_box = Label(gui,text='Encryption Key')
key_box.pack()
textfield_key = Entry(gui,justify=CENTER,font=('font',10),relief='solid')
textfield_key.pack(side=TOP,fill=X,padx=50,pady=10,ipady=10)
btn_en = Button(gui,text='Encrypt',width=7,height=1,relief='solid',activebackground='orange',activeforeground='#fff')
btn_en.pack(ipadx=7)
btn_en.bind('<Button-1>',click_btn)
title_h = Label(gui,text='Cipher Text',font=('kanit',22))
title_h.pack(pady=10)
textfield_d = Entry(gui,justify=CENTER,font=('font',15),relief='solid')
textfield_d.pack(side=TOP,fill=X,padx=30,pady=20,ipady=50)
gui.mainloop()
Output :
btn click
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\PAssWORD\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "c:\Users\PAssWORD\Music\encryt.py", line 19, in click_btn
des = DES.new(key, DES.MODE_ECB)
File "C:\Users\PAssWORD\AppData\Local\Programs\Python\Python39\lib\site-packages\Crypto\Cipher\DES.py", line 145, in new
return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
File "C:\Users\PAssWORD\AppData\Local\Programs\Python\Python39\lib\site-packages\Crypto\Cipher\__init__.py", line 79, in _create_cipher
return modes[mode](factory, **kwargs)
File "C:\Users\PAssWORD\AppData\Local\Programs\Python\Python39\lib\site-packages\Crypto\Cipher\_mode_ecb.py", line 216, in _create_ecb_cipher
cipher_state = factory._create_base_cipher(kwargs)
File "C:\Users\PAssWORD\AppData\Local\Programs\Python\Python39\lib\site-packages\Crypto\Cipher\DES.py", line 76, in _create_base_cipher
result = start_operation(c_uint8_ptr(key),
File "C:\Users\PAssWORD\AppData\Local\Programs\Python\Python39\lib\site-packages\Crypto\Util\_raw_api.py", line 232, in c_uint8_ptr
raise TypeError("Object type %s cannot be passed to C code" % type(data))
TypeError: Object type <class 'str'> cannot be passed to C code
You need to pass bytes instead of str to DES.new() and pad(), so change the following lines:
text1 = t_p
...
key = t_key
to
text1 = t_p.encode()
...
key = t_key.encode()
Also the logic of pad() function is incorrect, it should be like below:
def pad(text):
n = len(text) % 8
if n:
n = 8 - n
return text + (b' ' * n)
Also you have defined pad() twice.
Note that AES should be used instead of DES.
I have been working on a small project in which i can enter my test grades and have my computer calculate my current semester GPA. I just started and have been working on adding and deleting courses using tkinter.
I reached a point where adding a window inside my root window to add a new course started giving me an error in Tkinter:
Exception in Tkinter callback
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib
/python2.7/lib-tk/Tkinter.py", line 1536, in __call__
return self.func(*args)
TypeError: createCourseEntry() takes exactly 1 argument (0 given)
Here is my code:
from Tkinter import *
import tkMessageBox
course = list()
class Course:
course = list()
def __init__(self, longName, shortName, professor):
self.longName = longName
self.shortName = shortName
self.professor = professor
#staticmethod
def importCourses():
n=0
course[:] = []
with open('Courses.txt', 'r') as f:
for line in f:
if line == '\n':
continue
longName, shortName, professor = line.rstrip("\n\r").split('-')
course.append(Course(longName, shortName, professor))
n=n+1
#classmethod
def createCourse(cls, newLongName, newShortName, newProfessor):
with open('Courses.txt', 'r') as g:
lines = g.readlines()
with open('Courses.txt', 'a') as f:
for line in lines:
if ('-' + newShortName + '-') in line:
tkMessageBox.showinfo("Oops!", "There is already a Course with the name " + newShortName + '.')
return
f.write(newLongName + '-' + newShortName + '-' + newProfessor)
Course.importCourses()
#staticmethod
def createCourseEntry(self):
createCourseEntryWindow = Toplevel(self)
newCourseSNameLabel = Label(createCourseEntryWindow, text="Course Short Name:")
newCourseSNameLabel.grid(row=0,column=0)
newCourseLNameLabel = Label(createCourseEntryWindow, text="Course Long Name:")
newCourseLNameLabel.grid(row=1,column=0)
newCourseProfessorLabel = Label(createCourseEntryWindow, text="Course Professor:")
newCourseProfessorLabel.grid(row=2,column=0)
newCourseSNameEntry = Entry(createCourseEntryWindow)
newCourseSNameEntry.grid(row=0,column=1)
newCourseLNameEntry = Entry(createCourseEntryWindow)
newCourseLNameEntry.grid(row=1,column=1)
newCourseProfessorEntry = Entry(createCourseEntryWindow)
newCourseProfessorEntry.grid(row=2,column=1)
createNewCourseButton = Button(createCourseEntryWindow, text="Create",
command=Course.createCourse(newCourseSNameEntry.get(),newCourseLNameEntry.get(),newCourseProfessorEntry.get()))
createNewCourseButton.grid(row=3,column=0)
cancelCreation = Button(createCourseEntryWindow, text="Cancel", command=lambda win=top: win.destroy())
cancelCreation.grid(row=3,column=1)
def deleteCourse(deleteShortName):
with open('Courses.txt', 'r') as f:
lines = f.readlines()
with open('Courses.txt', 'w') as g:
for line in lines:
if ('-'+deleteShortName+'-') not in line:
g.write(line)
Course.importCourses()
def deleteCourseEntry(self):
deleteCourseEntryWindow = TopLevel(self)
deleteCourseLabel = Label(deleteCourseEntryWindow, text="Course Short Name:")
deleteCourseLabel.grid(row=0, column=0)
deleteCourseSNameEntry = Entry(deleteCourseEntryWindow)
deleteCourseSNameEntry.grid(row=0,column=1)
deleteCourseButton = Button(deleteCourseEntryWindow, text="Delete",
command=Course.deleteCourse(deleteCourseSNameEntry.get()))
deleteCourseButton.grid(row=1,column=0)
cancelDeletion = Button(deleteCourseEntryWindow, text="Cancel", command=lambda win=top: win.destroy())
cancelDeletion.grid(row=1,column=1)
Course.importCourses()
# Course.deleteCourse('LIT2380')
#Course.createCourse('Literature by Women','LIT2380','Alexandra Asbille')
root = Tk()
createCourseWindowButton = Button(root, text= 'Create Course', relief='solid', command=Course.createCourseEntry)
createCourseWindowButton.grid(row=0, column=0)
deleteCourseWindowButton = Button(root, text= 'Delete Course', relief='solid', command=Course.deleteCourseEntry)
deleteCourseWindowButton.grid(row=0, column=1)
courseSNameLabels = list()
courseLNameLabels = list()
courseProfessorLabels = list()
for x in range(0,len(course)):
courseSNameLabels.append(Label(root, text= course[x].shortName, relief='solid'))
for x in range(0,len(course)):
courseLNameLabels.append(Label(root, text= course[x].longName, relief='solid'))
for x in range(0,len(course)):
courseProfessorLabels.append(Label(root, text= course[x].professor, relief='solid'))
m=1
for y in courseSNameLabels:
y.grid(row=m)
m=m+1
m=1
for y in courseLNameLabels:
y.grid(row=m, column=1)
m=m+1
m=1
for y in courseProfessorLabels:
y.grid(row=m, column=2)
m=m+1
root.mainloop()
Obviously, there is no need to go through the whole code to find the problem but i added it just in case. The problem only showed up after i added the 'createCourseEntry' Method and when I clicked the createCourseWindowButton which is located right after the root = tk() line. I tried adding parentheses after the command function in those buttons but still got an error.
I have been trying to solve this for days. Would greatly appreciate the help.
from turtle import*
from math import*
def Xcord(R,r,p,t):
x= (R-r) * cos(t) - (r+p) * cos((R-r)//r*t)
def Ycord (R,r,p,t):
y= (R-r) * sin(t) - (r+p) * sin((R-r)//r*t)
def t_iter(R,r,p):
t=0
down()
goto(Xcord(R,r,p,t),Ycord(R,r,p,t))
while (t < 2 * pi):
t = t+.01
Xcord(R,r,p,t)
Ycord(R,r,p,t)
up()
return
def main():
R=100
r=4
p=int(input("Please enter a number between 10 and 100: "))
if p < 10 or p > 100:
input(" Incorrect value of p!")
t_iter(R,r,p)
input("Hit enter to close porgram")
bye()
main()
I get this error:
Traceback (most recent call last):
File "C:/Users/Coscio/Desktop/spirals.py", line 31, in <module>
main()
File "C:/Users/Coscio/Desktop/spirals.py", line 27, in main
t_iter(R,r,p)
File "C:/Users/Coscio/Desktop/spirals.py", line 13, in t_iter
goto(Xcord(R,r,p,t),Ycord(R,r,p,t))
File "<string>", line 1, in goto
File "D:\Python\lib\turtle.py", line 1774, in goto
self._goto(Vec2D(*x))
TypeError: type object argument after * must be a sequence, not NoneType
from turtle import*
from math import*
def Xcord(R,r,p,t):
return (R-r) * cos(t) - (r+p) * cos((R-r)//r*t)
def Ycord (R,r,p,t):
return (R-r) * sin(t) - (r+p) * sin((R-r)//r*t)
def t_iter(R,r,p):
t=0
up()
Xcord(R,r,p,t)
Ycord(R,r,p,t)
while (t < 2 * pi):
t = t+.01
goto(Xcord(R,r,p,t),Ycord(R,r,p,t))
down()
return float(Xcord(R,r,p,t))
return float(Ycord(R,r,p,t))
def validate():
while True:
p=int(input("Please enter a number between 10 and 100: "))
if p >= 10 or p <= 100:
break
return p
def main():
speed(0)
R=100
r=4
p = validate()
t_iter(R,r,p)
Xcord(R,r,p,t_iter(R,r,p))
Ycord(R,r,p,t_iter(R,r,p))
input("Hit enter to close porgram")
bye()
main()