I want to design a Gui script for a NameSort script.
I want to develop a python3 script with Gui. Here is my code for Cli only
text = open('/Users/test/Desktop/readme.txt','r')
def readtxt(txt): #turns txt to ls
dictls=(txt.read()).splitlines()
return dictls
def getdict(dictls): #turns to dictionary
dict1 = {dictls.index(i) : i for i in dictls}
return dict1
def getkey(diction,index): #getkey
return diction[index]
def randomord(x,z): #random order generator, won't generate repeditive numbers
import random
output = []
done = []
y = 0 #already generated
while y <= x:
rnum = random.randint(0,z)
if rnum not in done:
output.append(rnum)
done.append(rnum)
y+=1
return output
def main():
ls=readtxt(text)
while True:
print(f'\nThere are {len(ls)} names on the list.')
try:
h = int(input('Number of names to gen: '))
if h-1 <= len(ls)-1:
outls = [getkey(getdict(ls),i) for i in randomord(h-1,len(ls)-1)]
print('\n'.join(outls))
else:
print(f'[*]ERR: There are only {len(ls)} names on the list.')
except:
print('[*]ERR')
main()
Now I have tried these code
text = open('/root/Desktop/Python/gui/hell.txt','r')
def readtxt(txt): #turns txt to ls
dictls=(txt.read()).splitlines()
return dictls
def getdict(dictls): #turns to dictionary
dict1 = {dictls.index(i) : i for i in dictls}
return dict1
def getkey(diction,index): #getkey
return diction[index]
def randomord(x,z): #random order generator, won't generate repeditive numbers
import random
output = []
done = []
y = 0 #already generated
while y <= x:
rnum = random.randint(0,z)
if rnum not in done:
output.append(rnum)
done.append(rnum)
y+=1
return output
def main():
ls=readtxt(text)
while True:
print(f'\nThere are {len(ls)} names on the list.')
try:
h = int(input('Number of names to gen: '))
if h-1 <= len(ls)-1:
outls = [getkey(getdict(ls),i) for i in randomord(h-1,len(ls)-1)]
print('\n'.join(outls))
else:
print(f'[*]ERR: There are only {len(ls)} names on the list.')
except:
print('[*]ERR')
global startmain
startmain = 0
def test1():
startmain = 1
###########################
##########################
###################################
from tkinter import *
import tkinter as tk
window = tk.Tk()
p1 = tk.Label(
text="Thomas-name-sort",
fg="red",
bg='green',
width=10,
height=8
)
name_ent = tk.Label(text="输入生成数量Number of names to gen:")
entry = tk.Entry()
name_ent.pack()
entry.pack()
name = entry.get()
b1 = tk.Button(
text="auto-testing自检",
bg="blue",
fg="orange",
width=20,
height=5,
command=test1()
)
b1.pack()
if startmain == 1:
main()
#bind-zone
window.mainloop()
It does not work.
I want to design a Gui script for a NameSort script.
I could not bind the button with the function
T have tried "command=main()" and "button.bind("", func=main()"
Please help me!!!
To set a button's function in tkinter, you only pass the function itself in the command parameter i.e.
command = test1,
Not command = test1() as in this case you are just giving it the result of the function (which is None). This is so that it can execute the function each time the button is pressed.
If you want to provide in arguments for it to execute, you'll then have to use a lambda function:
command = lambda: test1(param1, param2),
You can find decent guides on buttons in tkinter here if you're interested
Related
I try to use the ID entry from the GUI to count the similar IDs in the Excel column.
I always get a 0 in the if-loop and red color shows.
But there are similar IDs in the column.
My code
l1 = tk.Label(tab2, text="Status Check")
l1.place(x=10, y=10)
l2 = tk.Label(tab2, text="ID")
l2.place(x=10, y=60)
ID = tk.Entry(tab2)
ID.place(x=80, y=60)
l2 = tk.Label(tab2, text="Status")
l2.place(x=10, y=100)
t1 = tk.Entry(tab2)
t1.place(x=80, y=100)
comment = tk.Label(tab2)
comment.place(x=240, y=100)
df = pd.read_excel(r'Excel.xlsx')
IDlist = df['ID'].tolist()
id = ID.get()
def immunity_check():
d = IDlist.count(id)
print(d)
if d >= 2:
t1.config(bg= "Green")
comment.configure(text="Fully vaccinated!")
elif d == 1:
t1.config(bg= "Yellow")
comment.configure(text="Vaccinated!")
else d <= 0:
t1.config(bg= "Red")
comment.configure(text="Not vaccinated!")
Can anyone give an advice on how to fix it?
I totally agree with furas comment. Thank him, he solved it.
Issue
Currently the code is reading the input from your text-field before button is pressed. Place a print(id) behind the ID.get() statement and watch console, like:
# GUI initialization omitted for brevity
df = pd.read_excel(r'Excel.xlsx') # read from Excel before button-pressed
IDlist = df['ID'].tolist()
id = ID.get() # get input from text-field before button-pressed
print(id)
# wait for a button press
# below is called on button-press and uses previously read id as argument
def immunity_check():
Solution
This is how you could solve it. The id should be read from text-input after button was pressed. So put move statement into the method:
# part 1: GUI initialization omitted for brevity
# part 2: define functions to call later
def read_ids():
df = pd.read_excel(r'Excel.xlsx')
return df['ID'].tolist()
def immunity_check():
id = ID.get() # read the id to search/count
d = id_list.count(id)
print(f"occurrences of id '{id}' in list: {d}")
if d >= 2:
t1.config(bg= "Green")
comment.configure(text="Fully vaccinated!")
elif d == 1:
t1.config(bg= "Yellow")
comment.configure(text="Vaccinated!")
else d <= 0:
t1.config(bg= "Red")
comment.configure(text="Not vaccinated!")
# part 3: main starts
id_list = read_ids()
# add button with trigger to function immunity_check()
button = tk.Button(tab2,text="Check",command=immunity_check) button.place(x=10,y=180)
The following code works for requesting input from a user through the Tkinter GUI and turning that input into a usable variable in the main script. However, any value that I put as the last in a list in the if statement (here "4") will hang and crash the program upon enter. This was also the case for "n" in a yes/no scenario. It also happens if I replace the if statement with a while not in [values] - the final value will crash the program. Is this just a quirk of Tkinter or is there something that I am missing?
import tkinter as tk
from tkinter import *
# get choice back from user
global result
badinput = True
while badinput == True:
boxwidth = 1
result = getinput(boxwidth).strip().lower()
if result in ['1', '2', '3', '4']:
badinput = False
# iterate through play options
if result == '1':
# Do Something
elif result =='2':
# Do Something
elif result =='3':
# Do Something
else:
# Do Something
def getinput(boxwidth):
# declaring string variable for storing user input
answer_var = tk.StringVar()
# defining a function that will
# get the answer and set it
def user_response(event):
answer_var.set(answer_entry.get())
return
answer_entry = tk.Entry(root, width = boxwidth, borderwidth = 5)
# making it so that enter calls function
answer_entry.bind('<Return>', user_response)
# placing the entry
answer_entry.pack()
answer_entry.focus()
answer_entry.wait_variable(answer_var)
answer_entry.destroy()
return answer_var.get()
In case anyone is following this question, I did end up solving my problem with a simple if statement within the callback. I can feed a dynamic "choicelist" of acceptable responses into the callback upon user return. If the answer is validated, the gate_var triggers the wait function and sends the program and user response back into the program.
'''
def getinput(boxwidth, choicelist):
# declaring string variable for storing user input
answer_var = tk.StringVar()
gate_var = tk.StringVar()
dumplist = []
# defining a function that will
# get the answer and set it
def user_response(event):
answer_var.set(answer_entry.get())
if choicelist == None:
clearscreen(dumplist)
gate_var.set(answer_entry.get())
return
if answer_var.get() in choicelist:
# passes a validated entry on to gate variable
clearscreen(dumplist)
gate_var.set(answer_entry.get())
else:
# return to entry function and waits if invalid entry
clearscreen(dumplist)
ErrorLabel = tk.Label(root, text = "That is not a valid response.")
ErrorLabel.pack()
ErrorLabel.config(font = ('verdana', 18), bg ='#BE9CCA')
dumplist.append(ErrorLabel)
return
global topentry
if topentry == True:
answer_entry = tk.Entry(top, width = boxwidth, borderwidth = 5)
else:
answer_entry = tk.Entry(root, width = boxwidth, borderwidth = 5)
# making it so that enter calls function
answer_entry.bind('<Return>', user_response)
# placing the entry
answer_entry.pack()
answer_entry.focus()
answer_entry.wait_variable(gate_var)
answer_entry.destroy()
return answer_var.get()
'''
Here is my code. I want my variable "a" to hold a default value 0 whenever the user has not given any particular value. I have given my code below:
from tkinter import *
from tkinter import messagebox
def sample():
a= show_values1()
v= int(a)+10
print (v)
def show_values1(event=None):
global a
a= i1.get()
print(a)
if int(a) > ul or int(a) < ll :
print('Limit Exceed')
messagebox.showerror("Error", "Please enter values from -100 to 100")
else :
return a
root= Tk()
ul= 100
ll=-100
i1 = inputBox = Entry()
i1.place(x=70, y=48, height=20)
bu1=Button(text='Enter', command = show_values1)
bu1.place(x = 70, y = 28, width=40, height=20)
bu2=Button(text='SEND', command = sample)
bu2.bind('<Return>', lambda x: show_values1(event=None))
bu2.place(x = 70, y = 98, width=40, height=20)
root.mainloop()
If no value has been entered, i1.get() will have a value of empty string "", so you could just test for that inside showvalues1:
if a == "":
return 0
As li.get() returns a string. Nothing entered will be a string of zero length. You can test for that and then set a to zero. For axample, after your a = i1.get() statement, insert:
if len(a) == 0:
a = "0"
Maybe you also need to handle cases where get() returns values that are not able to be cast to type int. :-)
I'm creating a program that allows the user to select a category and enter a value to calculate a charge. I would like to validate the text entry using my own validation file. However, when I run the program and enter nothing in the text entry, the error window keeps popping up over and over again. In addition, when I run the program and enter a valid number in the entry field, the charge comes out to 0.0, even though I have defined the calculation for the total charge.
Here is the program:
import tkinter
import tkinter.messagebox
import ValidationFile
validationObject = ValidationFile.ValidationClass ()
class MyGUI:
def __init__ (self):
self.main_window = tkinter.Tk ()
self.top_frame = tkinter.Frame (self.main_window)
self.middle_frame = tkinter.Frame (self.main_window)
self.bottom_frame = tkinter.Frame (self.main_window)
self.phone_var = tkinter.IntVar ()
self.phone_var.set (1)
self.pb1 = tkinter.Radiobutton (self.top_frame, \
text = 'Daytime (6:00 AM - 5:59 PM)', variable = self.phone_var, \
value = 0.12)
self.pb2 = tkinter.Radiobutton (self.top_frame, \
text = 'Evening (6:00 PM - 11:59 PM)', variable = self.phone_var, \
value = 0.07)
self.pb3 = tkinter.Radiobutton (self.top_frame, \
text = 'Off-Peak (Midnight - 5:50 AM)', variable = self.phone_var, \
value = 0.05)
#pack phone buttons
self.pb1.pack ()
self.pb2.pack ()
self.pb3.pack ()
#create input and output buttons
self.txtInput = tkinter.Entry (self.middle_frame, \
width = 10)
self.value = tkinter.StringVar ()
self.lblOutput = tkinter.Label (self.middle_frame, \
width = 10, textvariable = self.value)
self.txtInput.pack()
self.lblOutput.pack ()
#create OK buton and QUIT button
self.ok_button = tkinter.Button (self.bottom_frame, \
text = 'OK', command = self.show_choice)
self.quit_button = tkinter.Button (self.bottom_frame, \
text = 'QUIT', command = self.main_window.destroy)
#pack the buttons
self.ok_button.pack (side = 'left')
self.quit_button.pack (side = 'left')
#pack the frames
self.top_frame.pack ()
self.middle_frame.pack ()
self.bottom_frame.pack ()
#start the mainloop
tkinter.mainloop ()
def show_choice (self):
choice = self.phone_var.get ()
value = -1
while value == -1:
valueEntry = self.txtInput.get()
if valueEntry == '':
value = -1
tkinter.messagebox.showinfo (title = 'ERROR', \
message = 'Please enter a valid number.')
else:
value = validationObject.checkFloat (valueEntry)
total = choice * value
self.value.set (total)
#create instance of MyGUI class
my_GUI = MyGUI ()
Here is the validation file:
#create validation class
class ValidationClass:
def checkFloat (self, inputString):
try:
result = float (inputString)
except Exception:
return -1
if result < 0:
return -1
else:
return result
def checkInteger (self, inputString):
try:
result = int (inputString)
except Exception:
return -1
if result < 0:
return -1
else:
return result
You made an infinite loop with while value == -1:. Nowhere in that loop do you pause to allow the user to try again. You don't need the loop at all:
def show_choice (self):
valueEntry = self.txtInput.get()
value = validationObject.checkFloat(valueEntry)
if value == -1:
tkinter.messagebox.showinfo (title = 'ERROR', \
message = 'Please enter a valid number.')
else:
choice = self.phone_var.get()
total = choice * value
self.value.set (total)
Once you fix that you will have another problem: you use float values in your options but the variable is an IntVar, which can only handle integers. So "choice" will always be 0. You need to use DoubleVar instead.
Hello :) In the typing practice program I am creating in python 3, I have a for...loop that takes the characters from a global list of a certain paragraphs characters and compares it to the character the user is typing.
For some reason, the for loop wont iterate and won't go on to the next character. After some research, I figured out that you have to use local variables in order to do this but that doesn't work either. Here is my code:
import random
from tkinter import *
root=Tk()
a_var = StringVar()
words = []
eachword = []
global eachchar
charlist = []
x=random.randint(0,10)
def typingpractice():
realcharlist = []
something = []
paralist = []
#x=random.randint(0,10)
file = open("groupproject.txt")
line = file.readline()
paraWords = []
for line in file:
newline = line.replace("\n","")
paralist.append(line.replace("\n", ""))
paraWords.append(newline.split(" "))
wordList = []
for c in paraWords[x]:
charlist.append(c)
for b in range(0,len(charlist)):
wordList.append(charlist[b])
#print (wordList)
for p in charlist[b]:
realcharlist.append(p)
#print(realcharlist)
a=Canvas(root, width=500, height=500)
a.pack()
a.create_text(250,50, text = "Typing Fun", width = 500, font = "Verdana", fill = "purple")
a.create_text(250,300, text = paralist[x], width = 500, font = "Times", fill = "purple")
a = Entry(root, width = 100)
a.pack()
a.focus_set()
a["textvariable"] = a_var
def compare(s, realcharlist):
for g in realcharlist:
print ("s:",s)
print ("g:",g)
if s == g:
print ("y")
a['fg'] = 'green'
break
else:
print ("n")
a['fg'] = 'red'
break
def callback(*args):
global s
# print ("b:",xcount)
s = a.get()
s = s[-1:]
compare(s, realcharlist)
a_var.trace_variable("w", callback) #CALL WHEN VARIABLE IS WRITTEN
def practicetest():
print ("nothing here yet")
b = Button(root, text="Start Practice", command=typingpractice)
b.pack()
d = Button(root, text="Test", command=practicetest)
d.pack()
root.mainloop()
The text file "groupproject.txt" is an external text file that contains 10 one-line paragraphs, each character of each paragraph is being compared to what the user is typing in.
Any help on how to make the for loop work would be greatly appreciated. Thanks :D
Basically what happened was there was a break in the for loop so it would always iterate itself starting from 0 again.