CANT GET VALUE FROM ENTRY - python-3.x

I'm attempting to develop a registration form, but I can't get the value of the entries because nonetype and return self func are specified.
I tried entering values into the entries, but nothing worked. Again, we find that understanding some of the features and structure of your code is required before you can make modifications.
import tkinter as tk
from tkinter import *
from tkinter import ttk
class App():
# created window
# made all entries global
##################################################### ENTRIES #####################################################################
# some entries
def submit():
MsgBox = messagebox.askokcancel('FYEF',"stuff",icon = 'info')
if MsgBox == True:
# ENTRIES
enroll = enroll_code.get()
readonly = readonly_combo.get()
school = schools.get()
sc_did = sc_id.get()
sc_dd = sc_add.get()
vr = vrb.get()
if vr == 1:
vr = 'Private'
elif vrb == 2:
vr = 'Public'
PSA = PSA_no.get()
lr_no = lr_number.get()
last_nme = last_name.get()
first_nme = first_name.get()
mid_nme = mid_name.get()
ext_nme = ext_name.get()
birth_dte = birth_date.get()
ageyr = age.get()
vhr = vhar.get()
if vhr == 1:
vhr = 'Male'
elif vhr == 2:
vhr = 'Female'
iic = ip_ic.get()
if iic == 1:
iic = 'Yes'
elif iic == 2:
iic = 'No'
mother_ton = mother_tongue.get()
relgaff = relg_aff.get()
spneeds = sp_needs.get()
eadd = em_add.get()
hom_add = home_add.get()
f_name = fath_name.get()
f_contact = fath_contact.get()
m_name = moth_name.get()
m_contact = moth_contact.get()
g_name = guar_name.get()
g_contact = guar_contact.get()
m_wifi = means_wifi.get()
p_modal = pref_modal.get()
concern = concerns.get()
approve = approval.get()
tday = date.today()
dte = today.strftime("%B %d, %Y")
woot = tk.Tk()
wlc = ttk.Label(woot, text='🎊Welcome!', font='bold, 30').place(x=50,y=100)
# SUBMIT Button
submit_button = ttk.Button(tab_2, text="Submit", command=submit).place(x=655,y=700)
App()

Edit: Asked by Delrius Euphoria. The woot = tk.Tk(), app = App(), and woot.mainloop() should be outside of class . ttk.Label should be outside of function
Try this:
import tkinter as tk
from tkinter import *
from tkinter import ttk
woot = tk.Tk()
class App():
# created window
# made all entries global
##################################################### ENTRIES #####################################################################
# some entries
def submit():
MsgBox = messagebox.askokcancel('FYEF',"stuff",icon = 'info')
if MsgBox == True:
# ENTRIES
enroll = enroll_code.get()
readonly = readonly_combo.get()
school = schools.get()
sc_did = sc_id.get()
sc_dd = sc_add.get()
vr = vrb.get()
if vr == 1:
vr = 'Private'
elif vrb == 2:
vr = 'Public'
PSA = PSA_no.get()
lr_no = lr_number.get()
last_nme = last_name.get()
first_nme = first_name.get()
mid_nme = mid_name.get()
ext_nme = ext_name.get()
birth_dte = birth_date.get()
ageyr = age.get()
vhr = vhar.get()
if vhr == 1:
vhr = 'Male'
elif vhr == 2:
vhr = 'Female'
iic = ip_ic.get()
if iic == 1:
iic = 'Yes'
elif iic == 2:
iic = 'No'
mother_ton = mother_tongue.get()
relgaff = relg_aff.get()
spneeds = sp_needs.get()
eadd = em_add.get()
hom_add = home_add.get()
f_name = fath_name.get()
f_contact = fath_contact.get()
m_name = moth_name.get()
m_contact = moth_contact.get()
g_name = guar_name.get()
g_contact = guar_contact.get()
m_wifi = means_wifi.get()
p_modal = pref_modal.get()
concern = concerns.get()
approve = approval.get()
tday = date.today()
dte = today.strftime("%B %d, %Y")
wlc = ttk.Label(woot, text='🎊Welcome!', font='bold, 30').place(x=50,y=100)
enroll_code =ttk.Entry(woot).place(x=50,y=150)
# SUBMIT Button
submit_button = ttk.Button(woot, text="Submit", command=submit).place(x=655,y=700)
app = App()
woot.mainloop()

Related

How to check directory access attributes (permissions)?

I need to check access to the directory (permissions for groups) on Windows 8.1 / 10. The bottom line is that a situation is possible where all permissions or part of them are prohibited and, in this case, I do not want to throw expection, and even more so with errno.
It is necessary to understand in advance the function (s) that will show whether I will have WinError or PermissionError when reading/writing, for a specific group or all groups (SYSTEM, Administrator, etc.).
The standard stat library and os.access() did not give me the desired results. There are also options with changing permissions for the directory, but this may not always work, especially in usermode, which is why I try to do the verification.
I also tried to read the rights of the ACL, but nothing came of it because of inexperience.
Such conclusions were drawn from the following code (did I check it exactly like that? I don’t know.), And games with the directory security settings (I also changed the location of the directory to the desktop, my documents, %appdata% and other spaces intended for user data [Everything in C:\Users\% USER_NAME%\]. I thought it might be a mistake.), which always produced the same result (maybe sometimes slightly different, but this does not cancel the question).
The most important thing is that an Exception will be thrown if you try to do something with this directory that is not allowed by the rules, and execute in this way:
import os
import stat
def access(path, flag): return os.access(path, flag)
def isExists(path): return access(path, os.F_OK)
def isReadable(path): return access(path, os.R_OK)
def isWritable(path): return access(path, os.W_OK)
def isExecuteable(path): return access(path, os.X_OK)
def mstat(path, followsymlink = 1):
if isinstance(path, str):
info = os.stat(path)
if followsymlink and stat.S_ISLNK(info[stat.ST_MODE]):
return(os.lstat(path))
return(info)
return(os.fstat(path))
def _mode(path): return(mstat(path)[stat.ST_MODE])
def mode(path): return(stat.S_IMODE(_mode(path)))
def ifreg(path): return(stat.S_ISREG(_mode(path)))
def ifdir(path): return(stat.S_ISDIR(_mode(path)))
def ifchr(path): return(stat.S_ISCHR(_mode(path)))
def ifblk(path): return(stat.S_ISBLK(_mode(path)))
def iffifo(path): return(stat.S_ISFIFO(_mode(path)))
def iflnk(path): return(stat.S_ISLNK(_mode(path)))
def ifsock(path): return(stat.S_ISSOCK(_mode(path)))
def is_suid(path): return(_mode(path) & stat.S_ISUID == stat.S_ISUID)
def is_sgid(path): return(_mode(path) & stat.S_ISGID == stat.S_ISGID)
def is_svtx(path): return(_mode(path) & stat.S_ISVTX == stat.S_ISVTX)
def is_read(path): return(_mode(path) & stat.S_IREAD == stat.S_IREAD)
def is_write(path): return(_mode(path) & stat.S_IWRITE == stat.S_IWRITE)
def is_exec(path): return(_mode(path) & stat.S_IEXEC == stat.S_IEXEC)
def is_rwxu(path): return(_mode(path) & stat.S_IRWXU == stat.S_IRWXU)
def is_rusr(path): return(_mode(path) & stat.S_IRUSR == stat.S_IRUSR)
def is_wusr(path): return(_mode(path) & stat.S_IWUSR == stat.S_IWUSR)
def is_xusr(path): return(_mode(path) & stat.S_IXUSR == stat.S_IXUSR)
def is_rwxg(path): return(_mode(path) & stat.S_IRWXG == stat.S_IRWXG)
def is_rgrp(path): return(_mode(path) & stat.S_IRGRP == stat.S_IRGRP)
def is_wgrp(path): return(_mode(path) & stat.S_IWGRP == stat.S_IWGRP)
def is_xgrp(path): return(_mode(path) & stat.S_IXGRP == stat.S_IXGRP)
def is_rwxo(path): return(_mode(path) & stat.S_IRWXO == stat.S_IRWXO)
def is_roth(path): return(_mode(path) & stat.S_IROTH == stat.S_IROTH)
def is_woth(path): return(_mode(path) & stat.S_IWOTH == stat.S_IWOTH)
def is_xoth(path): return(_mode(path) & stat.S_IXOTH == stat.S_IXOTH)
path = 'C:\\ERROR_ACCESS_DENIED_SAMPLE'
print(f'''
mode = {mode(path)}
ifreg = {ifreg(path)}
ifdir = {ifdir(path)}
ifchr = {ifchr(path)}
ifblk = {ifblk(path)}
iffifo = {iffifo(path)}
iflnk = {iflnk(path)}
ifsock = {ifsock(path)}
is_suid = {is_suid(path)}
is_sgid = {is_sgid(path)}
is_svtx = {is_svtx(path)}
is_read = {is_read(path)}
is_write = {is_write(path)}
is_exec = {is_exec(path)}
is_rwxu = {is_rwxu(path)}
is_rusr = {is_rusr(path)}
is_wusr = {is_wusr(path)}
is_xusr = {is_xusr(path)}
is_rwxg = {is_rwxg(path)}
is_rgrp = {is_rgrp(path)}
is_wgrp = {is_wgrp(path)}
is_xgrp = {is_xgrp(path)}
is_rwxo = {is_rwxo(path)}
is_roth = {is_roth(path)}
is_woth = {is_woth(path)}
is_xoth = {is_xoth(path)}
isExists = {isExists(path)}
isReadable = {isReadable(path)}
isWritable = {isWritable(path)}
isExecuteable = {isExecuteable(path)}
''')
Output:
mode = 511
ifreg = False
ifdir = True
ifchr = False
ifblk = False
iffifo = False
iflnk = False
ifsock = False
is_suid = False
is_sgid = False
is_svtx = False
is_read = True
is_write = True
is_exec = True
is_rwxu = True
is_rusr = True
is_wusr = True
is_xusr = True
is_rwxg = True
is_rgrp = True
is_wgrp = True
is_xgrp = True
is_rwxo = True
is_roth = True
is_woth = True
is_xoth = True
isExists = True
isReadable = True
isWritable = True
isExecuteable = True
I would like to see Pure Python as an answer.
the os module does have the os.access function to check access:
os.access('/path/to/folder', os.W_OK) # W_OK is for writing, R_OK for reading, etc.

Class player - Animation stop first frame

Quick question. I have my Player Class, working perfectly. Except for a small detail. This is the class:
from dict.entity_dict import player, player_class
from collections import OrderedDict
import pyglet, random
key = pyglet.window.key
class Player(pyglet.sprite.Sprite):
dir_stand = "south"
dir_run = "south"
sprite_stand = 3
sprite_run = 3
image = None
s = 0
def __init__(self, game):
self.game = game
self.keyboard = key.KeyStateHandler()
self.statistics_base = OrderedDict()
self.image_stand = pyglet.resource.image(player.get("player_stand", {'x': None}).get("resource"))
self.image_run = pyglet.resource.image(player.get("player_run", {'x': None}).get("resource"))
self.image_stand_width = player.get("player_stand", {'x': None}).get("width")
self.image_stand_height = player.get("player_stand", {'x': None}).get("height")
self.image_run_width = player.get("player_run", {'x': None}).get("width")
self.image_run_height = player.get("player_run", {'x': None}).get("height")
self.vx = self.game.wd / 2
self.vy = self.game.wh / 2
self.load_sprite()
def class_player(self, type):
self.statistics_base["hp"] = player_class.get(type, {'x': None}).get("hp")
self.statistics_base["atk"] = player_class.get(type, {'x': None}).get("atk")
self.statistics_base["dif"] = player_class.get(type, {'x': None}).get("dif")
self.statistics_base["atk_sp"] = player_class.get(type, {'x': None}).get("atk_sp")
self.statistics_base["dif_sp"] = player_class.get(type, {'x': None}).get("dif_sp")
self.statistics_base["vel"] = player_class.get(type, {'x': None}).get("vel")
for stat in self.statistics_base:
if self.statistics_base[stat] is None:
self.statistics_base[stat] = 10
def animation(self, image, da, width, height):
frame_list = [image.get_region(x=width * i, y=height * da, width=46, height=58) for i in range(22)]
image_animation = pyglet.image.Animation.from_image_sequence(frame_list, 0.10, True)
return image_animation
def direction_sprite(self):
if self.dir_stand == "north":
self.sprite_stand = 7
elif self.dir_stand == "east":
self.sprite_stand = 5
elif self.dir_stand == "south":
self.sprite_stand = 3
elif self.dir_stand == "west":
self.sprite_stand = 1
if self.dir_run == "north":
self.sprite_run = 7
elif self.dir_run == "north-east":
self.sprite_run = 6
elif self.dir_run == "east":
self.sprite_run = 5
elif self.dir_run == "south-east":
self.sprite_run = 4
elif self.dir_run == "south":
self.sprite_run = 3
elif self.dir_run == "south-west":
self.sprite_run = 2
elif self.dir_run == "west":
self.sprite_run = 1
elif self.dir_run == "north-west":
self.sprite_run = 0
def load_sprite(self):
if not self.keyboard[key.W] and not self.keyboard[key.S] and not self.keyboard[key.D] and not self.keyboard[key.A]:
self.keyboard.clear()
img = self.image_stand
img_width = self.image_stand_width
img_height = self.image_stand_height
da = self.sprite_stand
else:
img = self.image_run
img_width = self.image_run_width
img_height = self.image_run_height
da = self.sprite_run
self.direction_sprite()
self.image = self.animation(img, da, img_width, img_height)
self.image.width, self.image.height = img_width, img_height
self.image.anchor_x, self.image.anchor_y = img_width // 2, img_height // 2
self.sprite = pyglet.sprite.Sprite(self.image, batch=self.game.Batch, group=self.game.GroupEntitySprite)
self.sprite.x = self.vx
self.sprite.y = self.vy
def key_player(self):
if self.keyboard[key.W]:
self.vy += 1
self.dir_stand = "north"
self.dir_run = "north"
if self.keyboard[key.S]:
self.vy -= 1
self.dir_stand = "south"
self.dir_run = "south"
if self.keyboard[key.D]:
self.vx += 1
self.dir_stand = "east"
self.dir_run = "east"
if self.keyboard[key.A]:
self.vx -= 1
self.dir_stand = "west"
self.dir_run = "west"
if self.keyboard[key.W] and self.keyboard[key.D]:
random1 = random.randint(1, 2)
if random1 == 1:
self.dir_stand = "north"
else:
self.dir_stand = "east"
self.dir_run = "north-east"
if self.keyboard[key.S] and self.keyboard[key.D]:
random2 = random.randint(1, 2)
if random2 == 1:
self.dir_stand = "south"
else:
self.dir_stand = "east"
self.dir_run = "south-east"
if self.keyboard[key.W] and self.keyboard[key.A]:
random3 = random.randint(1, 2)
if random3 == 1:
self.dir_stand = "north"
else:
self.dir_stand = "west"
self.dir_run = "north-west"
if self.keyboard[key.S] and self.keyboard[key.A]:
random4 = random.randint(1, 2)
if random4 == 1:
self.dir_stand = "south"
else:
self.dir_stand = "west"
self.dir_run = "south-west"
def update(self):
self.key_player()
self.load_sprite()
Since to update the Player's sprite, I need to call the "load_sprite" function, which causes the animation to be constantly called. As a result, the same animation does not appear and remains still at the first frame. So how could I solve?
Edit: Modified the script, including the for loop. If you see, I modified the group, using Batch and OrderedGroup instead. In this way we can clearly see the problem I am having.
The problem I have is due to the fact that pyglet.sprite.Sprite is called in order to update which animation is executed. However, doing so at the same time, the animations are not shown exactly because of the constant call of pyglet.sprite.Sprite.
First, you can change the sprite's animation by setting its image attribute, instead of creating a new Sprite instance. Second, only change its animation when you actually need to. That is when the direction changes.
I've added a simple example (pseudo) code to roughly show what I mean.
def animation(image, da, width, height):
frame_list = [image.get_region(x=width * i, y=height * da, width=46, height=58) for i in range(22)]
image_animation = pyglet.image.Animation.from_image_sequence(frame_list, 0.10, True)
return image_animation
class Player:
def __init__(self, standing_animations, running_animations):
# ... code ...
self.standing_animations = standing_animations # List of animations
self.running_animations = running_animations # List of animations
self.current_animation = standing_animations[0] # Just to have a default animation
self.previous_running_direction = None
self.previous_standing_direction = None
def load_sprite(self):
self.sprite.x = self.vx
self.sprite.y = self.vy
if self.previous_running_direction == self.dir_run and self.previous_standing_direction == self.dir_stand:
return # Don't do anything more in here
if not self.keyboard[key.W] and not self.keyboard[key.S] and not self.keyboard[key.D] and not self.keyboard[key.A]:
self.keyboard.clear()
self.current_animation = self.standing_animations[self.sprite_stand]
else:
self.current_animation = self.running_animations[self.sprite_run]
self.sprite.image = self.current_animation
def update(self):
self.previous_running_direction = self.dir_run
self.previous_standing_direction = self.dir_stand
self.key_player()
self.load_sprite()

TSP using genetic algorithm

How do I implement 'insert mutation' and 'cycle recombination' for a TSP problem using genetic algorithm in Python3?
Assume I have done the selection steps and now I have two parents for reproduction.
This is what I have done so far:
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 13 14:15:31 2016
#author: niloo
"""
import pandas as pd
import random
import numpy as np
from geopy.distance import great_circle as gcy
def read(file_name):
data = pd.DataFrame.from_csv(file_name, sep=" ")
data = np.array(data)
return data
def Dist(data):
# distance = []
for i in range(len(data)):
temp = []
for j in range(len(data)):
if j < i:
temp.append(distance[j][i])
elif i == j:
temp.append(0)
else:
temp.append(gcy((data[i][0], data[i][1]), (data[j][0], data[j][1])).km)
distance.append(temp)
#print(distance[1][2])
return distance
def k_fitness():
k = 50
t = 3
first_gener = []
how_fit = []
for i in range(0, k):
temp = np.random.permutation(535)
first_gener.append(temp)
for i in range(len(first_gener)):
sum_dis = 0
for j in range(0, 534):
temp1 = first_gener[i][j]
temp2 = first_gener[i][j + 1]
sum_dis += distance[int(temp1)][int(temp2)]
how_fit.append(sum_dis)
# print(how_fit)
race1 = np.random.randint(k, size=t)
winner1 = 9999999999999999999
for i in range(0, t):
if how_fit[int(race1[i])] < winner1:
winner1 = how_fit[int(race1[i])]
mom = first_gener[int(race1[i])]
#print (mom)
race2 = np.random.randint(k, size=t)
winner2 = 9999999999999999999
for i in range(0, t):
if how_fit[int(race2[i])] < winner2:
winner2 = how_fit[int(race2[i])]
dad = first_gener[int(race2[i])]
return mom, dad
def cross_over(mom , dad):
#mom = [1,2,3,4,5,6,7,8,9]
#dad = [9,3,7,8,2,6,5,1,4]
if len(mom) != len(dad):
print ('error')
else:
child1 = [0] * len(mom)
child2 = [0] * len(mom)
flag = False
index = [0] * len(mom)
while True:
ind = -1
for i in range(len(mom)):
if index[i] == 0:
ind = i
break
if ind == -1:
break
temp = ind
while True:
index[temp] = 1
if flag == False:
child1[temp] = mom[temp]
child2[temp] = dad[temp]
else:
child1[temp] = dad[temp]
child2[temp] = mom[temp]
val = dad[temp]
for i in range(len(dad)):
if mom[i] == val:
temp = i
break
if ind == temp:
break
if flag == False:
flag = True
else:
flag = False
#print child1
#print child2
return [child1 , child2]
def mutation(offspring):
if random.random() <= 0.02:
index1 = random.randint(534)
index2 = random.randint(534)
if index1 != index2:
ind1 = min(index1 , index2)
ind2 = max(index1 , index2)
temp = offspring [ : ind1+1]
temp += offspring [ind2 : ind2+1]
temp += offspring [ind1+1 : ind2]
temp += offspring [ind2+1 : ]
offspring = temp
return offspring
else:
return offspring
dat = read('ali535.tsp')
distance = []
Dist(dat)
k_fitness()

Python quiz, using tkinter

from tkinter import *
import tkinter as tk
q = 0
s = -1
count = 0
correct = 0
incorrect = 0
question = ["Is this a quiz","Are you sure","Dont be","see its not a quiz"]
answer = ["yes","yes","ok","ok"]
answer_cap = ["Yes","Yes","Ok","Ok"]
root = Tk()
name = tk.Label(root,text = "GUI Quiz")
name.pack()
label = tk.Label(root,text = question[0])
label.pack()
entry = tk.Entry(root)
entry.pack()
def out():
global q,correct,incorrect,s,count
count = count + 1
ans = entry.get()
print (ans)
print (question[q])
print (answer[q])
if count < 4:
if answer[q] or answer_cap[q] == ans :
q = q + 1
entry.delete(0, END)
correct = correct + 1
label.config(text = question[q])
else:
q = q + 1
entry.delete(0, END)
incorrect = incorrect + 1
label.config(text = question[q])
else:
entry.delete(0, END)
label.config(text = "Correct: "+str(correct) + " Incorrect: "+str(incorrect))
def stop():
global q,correct,incorrect
q = 0
correct = 0
incorrect = 0
entry.delete(0, END)
label.config(text = question[0])
button = tk.Button(root,text = "Submit",command = out)
button.pack()
button_two = tk.Button(root,text = "Restart",command = stop)
button_two.pack()
root.mainloop()
nothing actually wrong with the code its just how I'm doing it. When I run module it will ask my four questions and I will give the answer, but no matter what I put it will say I got 3 correct and none wrong. Am I missing something obvious or is it how I layed out the code.
The first part of your out function should not have 'count = count + 1' because this adds one to you score regardless of weather you were right or wrong; relocate the commented code.
def out():
global q,correct,incorrect,s,count
#count = count + 1
ans = entry.get()
print (ans)
print (question[q])
print (answer[q])

Python 3 - How do I replace all letters in a sentence with their respective keys in a dictionary

So I'm creating a program that allows you to set each letter in the alphabet to another one using a dictionary. It then lets you input a sentence, which it then codes using the code you previously set. So far, I've completed (or I think I've completed) everything but the function that replaces the letters, because I have no idea what to do there. Any suggestions?
Here's the code:
import sys
def defineAlphabet():
alphabet = dict()
alphabet['a'] = input('a = ')
alphabet['b'] = input('b = ')
alphabet['c'] = input('c = ')
alphabet['d'] = input('d = ')
alphabet['e'] = input('e = ')
alphabet['f'] = input('f = ')
alphabet['g'] = input('g = ')
alphabet['h'] = input('h = ')
alphabet['i'] = input('i = ')
alphabet['j'] = input('j = ')
alphabet['k'] = input('k = ')
alphabet['l'] = input('l = ')
alphabet['m'] = input('m = ')
alphabet['n'] = input('n = ')
alphabet['o'] = input('o = ')
alphabet['p'] = input('p = ')
alphabet['q'] = input('q = ')
alphabet['r'] = input('r = ')
alphabet['s'] = input('s = ')
alphabet['t'] = input('t = ')
alphabet['u'] = input('u = ')
alphabet['v'] = input('v = ')
alphabet['w'] = input('w = ')
alphabet['x'] = input('x = ')
alphabet['y'] = input('y = ')
alphabet['z'] = input('z = ')
return alphabet
def codeSentence(sentence):
global translation
translation = 'WIP'
return translation
def menu():
print('''Would you like to:
a. Code a sentence
b. Set the code
c. Quit''')
userInput = input('//> ')
if userInput == 'a':
codeSentence(input('Enter Sentence: '))
print(translation)
menu()
if userInput == 'b':
defineAlphabet()
print('Defined!')
menu()
if userInput == 'c':
print('Goodbye!')
sys.exit(0)
else:
print('That is not an option.')
menu()
menu()
result = "some sentence".translate({ord(k): v for k, v in alphabet.items()})
See str.translate().

Resources