https://github.com/Rodneyst/lv100roxas-gmail.com/blob/master/finalproject
Can look over the full code here. The link goes to the full code, I pull all the answer with one button using stringvar. Please answer I have 2 days left and haven't had any luck.
# Username widget
self.prompt_label5 = tkinter.Label(self.top_frame,
text='Enter your Name:' ,bg="red", fg="yellow", font="none 12 bold")
self.name_entry = tkinter.Entry(self.top_frame,
width=10)
# weight widget
self.prompt_label1 = tkinter.Label(self.top_frame,
text='Enter your weight(lbs):' ,bg="red", fg="yellow", font="none 12 bold")
self.weight_entry = tkinter.Entry(self.top_frame,
width=10)
def getworkout(self):
weight = float(self.weight_entry.get())
height = float(self.height_entry.get())
How would I validate these user inputs? Please help — I cannot figure it out. I want to get a pop-up window to show when the user inputs an integer for name and when they enter a string for weight and height, ValueErrors. Please help!
Code is messy, so make it look better :) But I think it does, what you asked about. I edited it in a hurry. Name also accept more signs then just letters (excluding integers) - it's easy to validate if necessery.
import tkinter
from tkinter import ttk
from tkinter import messagebox
import random
# GUI
class WorkoutGUI:
def __init__(self):
# Main window
self.main_window = tkinter.Tk()
self.main_window.title("Workout Generator")
self.main_window.geometry('1200x600')
# Frames
self.top_frame = tkinter.Frame()
self.mid_frame = tkinter.Frame()
self.bottom_frame = tkinter.Frame()
validation1 = self.top_frame.register(entry_validation_1)
validation2 = self.top_frame.register(entry_validation_2)
# TOP FRAME
# username widget
self.prompt_label1 = tkinter.Label(self.top_frame,
text='Enter your Name:', bg="red", fg="yellow", font="none 12 bold")
self.name_entry = tkinter.Entry(self.top_frame,
width=10, validate='key', validatecommand=(validation1, '%S'))
# weight widget
self.prompt_label2 = tkinter.Label(self.top_frame,
text='Enter your weight(lbs):', bg="red", fg="yellow", font="none 12 bold")
self.weight_entry = tkinter.Entry(self.top_frame,
width=10, validate='key', validatecommand=(validation2, '%S'))
# height widget
self.prompt_label3 = tkinter.Label(self.top_frame,
text='Enter your height(in):', bg="red", fg="yellow",
font="none 12 bold")
self.height_entry = tkinter.Entry(self.top_frame,
width=10, validate='key', validatecommand=(validation2, '%S'))
# gender widget
self.prompt_label4 = tkinter.Label(self.top_frame,
text='Select your gender:', bg="red", fg="yellow",
font="none 12 bold")
self.gender_entry = tkinter.IntVar()
self.gender_entry.set(1)
# radio buttons for gender choice
self.rb1 = tkinter.Radiobutton(self.top_frame,
text='Male',
variable=self.gender_entry,
value=1)
self.rb2 = tkinter.Radiobutton(self.top_frame,
text='Female',
variable=self.gender_entry,
value=2)
# goal widget
self.prompt_label5 = tkinter.Label(self.top_frame,
text='Select your goal:', bg="red", fg="yellow",
font="none 12 bold")
self.goal_entry = tkinter.IntVar()
self.goal_entry.set(1)
# radio buttons for goal choice
self.rb3 = tkinter.Radiobutton(self.top_frame,
text='Lose Weight',
variable=self.goal_entry,
value=1)
self.rb4 = tkinter.Radiobutton(self.top_frame,
text='Maintain',
variable=self.goal_entry,
value=2)
self.rb5 = tkinter.Radiobutton(self.top_frame,
text='Build Muscle Mass',
variable=self.goal_entry,
value=3)
# packing widgets
self.prompt_label1.pack(side='top')
self.name_entry.pack(side='top')
self.prompt_label2.pack(side='top')
self.weight_entry.pack(side='top')
self.prompt_label3.pack(side='top')
self.height_entry.pack(side='top')
self.prompt_label4.pack(side='top')
self.rb1.pack(side='top')
self.rb2.pack(side='top')
self.prompt_label5.pack(side='left')
self.rb3.pack(side='left')
self.rb4.pack(side='left')
self.rb5.pack(side='left')
# MIDDLE FRAME
self.descr_label = tkinter.Label(self.mid_frame,
text='Workout for you:')
self.value = tkinter.StringVar()
self.workout_label = tkinter.Label(self.mid_frame,
textvariable=self.value,
width=250, height=20, bg="white")
# packing widgets
self.descr_label.pack(side='top')
self.workout_label.pack(side='bottom')
# BOTTOM FRAME
# buttons
self.display_button = tkinter.Button(self.bottom_frame,
text='Get Workout!',
command=self.getworkout)
self.quit_button = tkinter.Button(self.bottom_frame,
text='Quit',
command=self.main_window.destroy)
# pack the buttons
self.display_button.pack(side='left')
self.quit_button.pack(side='right')
# packing frames
self.top_frame.pack()
self.mid_frame.pack()
self.bottom_frame.pack()
# fucnction to get outputs
def getworkout(self):
# Gather User information
name = str(self.name_entry.get())
gymSerial = random.randint(0, 10000)
weight = float(self.weight_entry.get())
height = float(self.height_entry.get())
gender = (self.gender_entry.get())
goal = (self.goal_entry.get())
def entry_validation_1(x):
if x.isdecimal():
messagebox.showwarning("Wrong input!", "Name must be a string - not integer.")
return False
else:
return True
def entry_validation_2(y):
if y.isdecimal():
return True
else:
messagebox.showwarning("Wrong input!", "Weight and height must be a numerical value - not string")
return False
def main():
root = tkinter.Tk()
ex = WorkoutGUI()
root.mainloop()
if __name__ == '__main__':
main()
Link is not working, but I wrote my own code as an example. I think it's very close to what you need.
The method is called entry validation and you can find some more info here:
https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/entry-validation.html
Feel free to ask if you have any concerns :)
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
# tkinter main window
root = tk.Tk()
root.title('Validation')
root.geometry('300x300')
def entry_validation_1(x):
if x.isdecimal():
messagebox.showwarning("Wrong input!", "Name must be a string - not integer.")
return False
else:
return True
def entry_validation_2(y):
if y.isdecimal():
return True
else:
messagebox.showwarning("Wrong input!", "Weight and height must be a numerical value - not string")
return False
validation1 = root.register(entry_validation_1)
validation2 = root.register(entry_validation_2)
name = tk.Entry(root, width='9', justify='center', validate='key', validatecommand=(validation1, '%S'))
weight_or_height = tk.Entry(root, width='9', justify='center', validate='key', validatecommand=(validation2, '%S'))
label_name = tk.Label(root, text='name - INTEGER NOT ACCEPTED')
label_weight_or_height = tk.Label(root, text='weight or height - STRING NOT ACCEPTED')
name.grid(row=0, column=0, padx=0, pady=0)
label_name.grid(row=0, column=1, padx=0, pady=0)
weight_or_height.grid(row=1, column=0, padx=0, pady=0)
label_weight_or_height.grid(row=1, column=1, padx=0, pady=0)
tk.mainloop()
Related
I've written a program where the UI displays a button that says "Enter Brewer Info" and once the user clicks that button, it calls the function "option1()" as a callback. The function option1() then calls brewers() function and gets user input to assign the values for num_brewer and brewer which is then returned in that function. The num_brewer and brewer var is then assigned as a global variable in option1() and global brewer_flag is set to 1.
Inside the while loop, it checks to see if brewer_flag is set to 1 and if not, it prints "Please select '1' to enter the brewer information first:". Once the user has entered the brewer info and brewer_flag is set to 1 (in option1 function), it's supposed to display "Brewers Selected: "+str(brewer)+" in the label but even after i enter brewer info and brewer_flag is set to 1, it still prints "Please select '1' to enter the brewer information first:" in the label and doesn't change the label to display the brewer array.
What exactly am i doing wrong?
(Im also aware that my while loop needs to exit by making leave = 1 but I'm doing that later)
import errno
from tkinter import *
from tkinter import messagebox
import os
import sys
import math
import numpy as np
import time
import subprocess
import socket
root = Tk()
root.title("Creator.py GUI")
root.config(bg="#17173c")
root.geometry("800x400")
global brewer_flag
#TKINTER FUNCTIONS TO REDUCE REPETITIVE CODE
def print_output(textinput, width, height):
new_window = Toplevel(root)
new_window.geometry("{}x{}".format(width, height))
new_window.title("")
new_window.config(bg="black")
label2 = Label(new_window, text=textinput, bg="black", fg="red")
label2.grid(row=0, column=0)
button10 = Button(new_window, text="Ok", width = 5, font="System 20", bg="green", fg="black", activebackground="black", activeforeground="red", borderwidth=5, cursor="hand2", highlightthickness=0, highlightcolor="black", highlightbackground="black", command=lambda: new_window.destroy())
button10.grid(row=1, column=0)
var = StringVar()
def get_input(textinput, width, height):
new_window = Toplevel(root)
new_window.geometry("{}x{}".format(width, height))
new_window.title("")
new_window.config(bg="#17173c")
label2 = Label(new_window, text=textinput)
label2.grid(row=0, column=0)
def return_value():
var.set(entry1.get())
entry1 = Entry(new_window)
entry1.grid(row=0, column=1)
button10 = Button(new_window, text="Ok", width = 10, font="System 20", bg="green", fg="black", activebackground="black", activeforeground="red", borderwidth=5, cursor="hand2", highlightthickness=0, highlightcolor="black", highlightbackground="black", command=lambda: [return_value(), new_window.destroy()])
button10.grid(row=1, column=0)
new_window.wait_variable(var)
#print(var.get())
return var.get()
def brewers():
#print("test")
flag = 1
while (flag==1):
try:
num_brewer=int(get_input("Number of brewers? (1-4): ", 400, 60))
#num_brewer=int(input("Number of brewers? (1-4): "))
#brewerInfo()
#num_brewer=int(val)
if (1 <= num_brewer <= 4):
flag=0
else:
error="Invalid input, try again"
print_output(error, 300, 100)
except ValueError:
error="Invalid input, input must be an interger"
print_output(error, 300, 100)
#brewer = [input("Enter the brewer # (ie: 024): ")]
brewer = [get_input("Enter the brewer # (ie: 024): ", 400, 60)]
for x in range (1, num_brewer):
print (brewer)
brewer.append(get_input("Enter the brewer # (ie: 024): ", 400, 60))
#brewer_flag= 1
return brewer, num_brewer
#########################################START OF PROGRAM###################################################
leave=0
brewer_flag = 0
while (leave==0):
if (brewer_flag == 1):
#make it a label on the home page
brewerselect = "Brewers Selected: "+str(brewer)+""
else:
#make it a label on the home page
brewerselect= "Please select '1' to enter the brewer information first:"
label2 = Label(root, text=brewerselect, bg="grey", fg="black")
def option1():
global brewer, num_brewer
brewer, num_brewer=brewers()
global brewer_flag
brewer_flag=1
#brewerselected="Brewers Selected: "+str(brewer)
#print(brewerselected)
button1 = Button(root, text="Enter brewer INFO", width = 40, font="System 20", bg="red", fg="black", activebackground="black", activeforeground="red", borderwidth=5, cursor="hand2", highlightthickness=0, highlightcolor="black", highlightbackground="black", command= option1)
label2.pack()
button1.pack()
# window in mainloop:
root.mainloop()
print ("Bye!")
exit(0)
In my code, I have tried to get the user input through text fields, store them in variables and finally print them in a tabular form.
The problem I am facing is that none of the values I enter through the text fields get displayed; when I try printing the variables, they come up empty.
Here's part of my code:
# SPASC
from tkinter import *
import tkinter as tk
import tkinter.ttk as tktrv
root = tk.Tk()
root.title("SPASC")
root.geometry("410x400")
lb1 = Label(root, text="SPASC \n Welcomes You !!!", fg="red", bg="sky blue"
, font=('Arial Black', 20), width=22, anchor=CENTER)
lb2 = Label(root, text="What would you like to compare?",
font=('Arial', 18), anchor=CENTER)
space1 = Label(root, text="\n\n")
lb1.grid(row=0)
lb2.grid(row=5)
space1.grid(row=1)
hpw, mil = StringVar(), StringVar()
def bt_cars():
w1 = Toplevel()
w1.title("Choose Features")
w1.geometry("430x200")
lb3 = Label(w1, text="Choose features for comparison", bg="yellow"
, font=('Arial Black', 18), width=25)
lb4 = Label(w1, text=" ", anchor=CENTER)
fr1 = LabelFrame(w1, width=20, padx=100)
hpw_cb = Checkbutton(fr1, text="Horsepower", variable=hpw, anchor='w', onvalue="Horsepower", offvalue="")
hpw_cb.grid()
hpw_cb.deselect()
mil_cb = Checkbutton(fr1, text="Mileage", variable=mil, anchor='w', onvalue="Mileage", offvalue="")
mil_cb.grid()
mil_cb.deselect()
var_stor = [hpw, mil]
print(hpw)
print(mil)
var_fill = []
for itr1 in var_stor:
if itr1 != "":
var_fill.append(itr1)
print(var_fill)
def car_1():
name1 = StringVar()
c1 = Toplevel()
c1.title("Car 1")
c1.geometry("430x200")
car1_lb1 = Label(c1, text="Car Name:")
name1_ifl = Entry(c1)
name1 = name1_ifl.get()
elm_var_fill = len(var_fill)
ct1 = 0
car1_val = []
for itr2 in var_fill:
if ct1 == elm_var_fill:
break
lb5 = Label(c1, text=itr2.get())
#Creating text field
ftr1_ifl = Entry(c1)
car1_ftr = ftr1_ifl.get()
car1_val.append(car1_ftr)
car1_ftr = None
lb5.grid(row=ct1 + 2, column=1)
ftr1_ifl.grid(row=ct1 + 2, column=2)
ct1 += 1
print(car1_val)
def display():
dp = Toplevel()
dp.title("Results")
dp.geometry("500x200")
car1_pt = 0
car2_pt = 0
car_tree = tktrv.Treeview(dp)
car_tree["columns"] = ("car1col")
car_tree.column("#0", width=120, minwidth=30)
car_tree.column("car1col", width=120, minwidth=30)
car_tree.heading("#0", text="Features" )
car_tree.heading("car1col", text=str(name1))
car_tree.pack()
c1.withdraw()
print(var_fill)
done1_bt = Button(c1, text="Continue", command=display)
name1_ifl.grid(row=0, column=2)
car1_lb1.grid(row=0, column=1)
done1_bt.grid(row=5,column=1)
w1.withdraw()
done_bt = Button(w1, text="Done", command=car_1)
done_bt.grid(row=3, column=1)
lb3.grid(row=0, column=1)
lb4.grid(row=1, column=1)
fr1.grid(row=2, column=1)
root.withdraw()
bt1 = Button(root, text="CARS", width=5, font=('Calibri', 15), command=bt_cars)
bt1.grid(row=7)
space2 = Label(root, text="\n\n")
space2.grid(row=6)
root.mainloop()
I am facing trouble with the variables named: hpw, mil, name1.
Any help would be welcome.
NOTE:- Please excuse the amount of code; I wanted others to replicate the error and see it for themselves
For the variables hpw and mil, these variables are empty strings that's why you are not getting any value from those checkboxes. To get values from the checkboxes replace these lines of code:
var_stor = [hpw, mil]
with
var_stor = [hpw_cb.cget('onvalue'), mil_cb.cget('onvalue')]
since you want the onvalue then you must use cget() method to access those values.
also, replace
lb5 = Label(c1, text=itr2.get())
with
lb5 = Label(c1, text=itr2)
because now you have required values (not objects) in a list, so just need to access those values.
For the variable name1 you can use #BokiX's method.
The problem is you are using get() wrong. You cannot use get() right after Entry() because as soon as entry is created it's getting the input before the user can even input something.
Use this code:
def get_input(text):
print(text)
e = Entry(root)
e.pack()
b = Button(root, text="Print input", command=lambda: get_input(e.get()))
b.pack()
Now get() method will not be executed before you click the button.
hello i want to make 3 checkboxes one saying cpu, one saying gpu and one saying cll
and i want to check if the answer is correct so can u show me how to do that
import time
import tkinter as tk
import pygame
window = tk.Tk()
pygame.mixer.init()
img = tk.PhotoImage(file='C:\\Users\\laithmaree\\PycharmProjects\\create_apps_with_python\\brainicon.ico.png')
window.title("Quiz Game")
# pygame.mixer.music.load('ForestWalk-320bit.wav')
# pygame.mixer.music.play()
# i created an icon
# i made a title
window.geometry("800x600")
window.resizable(width=False, height=False)
window.iconphoto(False, img)
label1 = tk.Label(window, text='Quiz App', font=("Arial Bold", 25))
label1.pack()
txtbox = tk.Entry(window, width=50)
def playbuttonclicked():
label1.destroy()
playbtn.destroy()
quitbtn.destroy()
label2 = tk.Label(window, text='What is the short form of computer science',font=("Arial Bold", 25))
label2.pack()
txtbox.place(x=250, y=200, height=40)
def chkanswer():
useranswer = txtbox.get() # Get contents from Entry
if useranswer == 'cs':
lblcorrect = tk.Label(window, text='correct', )
lblcorrect.pack()
def delete():
lblcorrect.destroy()
label2.destroy()
txtbox.destroy()
submitbtn.destroy()
label3 = tk.Label(window, text='whats is the short form of central proccessing unit', font=('Arial Bold', 25))
label3.pack()
lblcorrect.after(1001, delete)
else:
lblwrong = tk.Label(window, text='Try Again')
lblwrong.pack()
def deletefunction():
lblwrong.destroy()
lblwrong.after(1000, deletefunction)
submitbtn = tk.Button(window, text='Submit', font=('Arial Bold', 30), command=chkanswer, bg='red')
submitbtn.place(x=305, y=400)
submitbtn.bind('<Enter>', lambda e: e.widget.config(bg='grey'))
submitbtn.bind('<Leave>', lambda e: e.widget.config(bg='red'))
playbtn = tk.Button(window, text='Play', font=("Arial Bold", 90), bg='red', command=playbuttonclicked)
playbtn.place(x=10, y=200)
playbtn.bind('<Enter>', lambda e: e.widget.config(bg='grey'))
playbtn.bind('<Leave>', lambda e: e.widget.config(bg='red'))
def quitbuttonclicked():
window.destroy()
quitbtn = tk.Button(window, text='Quit', font=("Arial Bold", 90), bg='red', command=quitbuttonclicked)
quitbtn.place(x=400, y=200)
quitbtn.bind('<Enter>', lambda e: e.widget.config(bg='grey'))
quitbtn.bind('<Leave>', lambda e: e.widget.config(bg='red'))
window.mainloop()
the question is label 3 (whats is the short form of central proccessing unit) and i want to make sure the answer is correct because i am creating a quiz app thx
Here is a minimal example of how to create a Checkbutton and to attach a boolean variable and event to it:
import tkinter as tk
window = tk.Tk()
# callback for checkbutton
def checkbox_callback():
is_checked = checkbox_var.get()
print(f"The checkbox is selected: " + str(is_checked))
# variable to store the current value of the checkbutton
checkbox_var = tk.BooleanVar()
# checkbutton with text, variable and callback
checkbox = tk.Checkbutton(window, text="Click me", variable=checkbox_var, command=checkbox_callback)
checkbox.pack()
window.mainloop()
I got this problem. when I write secretframe() I get a empty box any ideas to fix this? Also how can I put a little space between the 2 frames.
I'm new to tkinter and any tips is gladly appreciated.
import tkinter as tk
import time
import math
##----------Functions
root = tk.Tk()
def Pi():
pi = math.pi
x = list(str(pi))
map(int,x)
print(math.pi)
def Unfinished():
print("This Button is not finished")
def secretframe(frame):
secrett = tk.Toplevel()
sframe = tk.Frame(secrett, height="300", width="300", bg="PeachPuff")
sLabel = tk.Label(sframe, text="Secret")
sframe.grid
sLabel.grid
##Defining
##Frames
frame = tk.Frame(root, height="300", width="300", bg="Black")
Mframe = tk.Frame(root, height="300", width="300", bg="White")
##WIdgets
Label = tk.Label(frame, text="R1p windows", bg="Black", fg="White")
Label2 = tk.Label(Mframe, text="Math magic", bg="White", fg="Black")
Knapp = tk.Button(frame, text="ok(ADMIN)", fg="White", bg="Black", font="monospace")
PIKnapp = tk.Button(Mframe, text="Pi(WIP)(UNFINISHED)", bg="White", fg="Black", font="Times")
##Config and bindings
Knapp.config(command=Unfinished)
PIKnapp.config(command=Pi)
##Packing
## Frame 1
Label.grid()
frame.grid()
Knapp.grid()
## Frame 2
Label2.grid()
Mframe.grid()
PIKnapp.grid()
You've forgotten the brackets. Try:
sframe.grid ()
sLabel.grid ()
Any ideas why the leftresult_label label does not update? The function seems to work but the label does not update. I have looked everywhere and can't find an answer. The 'left' value gets set but the label does not change.
from tkinter import *
root = Tk(className="Page Calculator")
read = IntVar()
total = IntVar()
left = IntVar()
read.set(1)
total.set(1)
left.set(1)
read_label = Label(root,text="Pages Read:")
read_label.grid(column=1, row=1)
total_label = Label(root,text="Total Pages:")
total_label.grid(column=1, row=2)
read_entry = Entry(root,textvariable=read)
read_entry.grid(column=2, row=1)
total_entry = Entry(root,textvariable=total)
total_entry.grid(column=2, row=2)
def func1():
left.set(total.get() - read.get())
print(left.get())
calculate_button = Button(root,text="Calculate",command= func1)
calculate_button.grid(column=2, row=3)
percenet_label = Label(root,text="Percent Finished:")
percenet_label.grid(column=1, row=4)
left_label = Label(root,text="Pages Left:")
left_label.grid(column=1, row=5)
percenetresult_label = Label(root,text=left.get())
percenetresult_label.grid(column=2, row=4)
leftresult_label = Label(root,text="")
leftresult_label.grid(column=2, row=5)
root.mainloop()
To make the function do the job, you'd rather have your label:
leftresult_label = Label(root, textvariable=left)
Once it's tkinter class variable, tkinter takes care about when you change the value. Once you click the button,
def func1():
left.set(total.get() - read.get())
percent.set(int(read.get()*100/total.get()))
left and percent values, which are instances of tkinter.IntVar() class have immidiate effect on widgets (labels in this case) where those values are set as textvariable, just as you have it at Entry widgets.
Here is full code:
from tkinter import *
root = Tk(className="Page Calculator")
read = IntVar()
total = IntVar()
left = IntVar()
percent = IntVar()
read.set(1)
total.set(1)
left.set(1)
percent.set(1)
def func1():
left.set(total.get() - read.get())
percent.set(int(read.get()*100/total.get()))
read_label = Label(root,text="Pages Read:")
read_label.grid(column=1, row=1)
read_entry = Entry(root,textvariable=read)
read_entry.grid(column=2, row=1)
total_label = Label(root,text="Total Pages:")
total_label.grid(column=1, row=2)
total_entry = Entry(root,textvariable=total)
total_entry.grid(column=2, row=2)
calculate_button = Button(root,text="Calculate",command= func1)
calculate_button.grid(column=2, row=3)
percenet_label = Label(root,text="Percent Finished:")
percenet_label.grid(column=1, row=4)
left_label = Label(root,text="Pages Left:")
left_label.grid(column=1, row=5)
percenetresult_label = Label(root,textvariable=percent)
percenetresult_label.grid(column=2, row=4)
leftresult_label = Label(root,textvariable=left)
leftresult_label.grid(column=2, row=5)
root.mainloop()
code including progress bar. update_idletasks() used to keep label and progress bar running.
from tkinter import *
from tkinter import ttk
root = Tk()
root.title('Counter Test')
root.iconbitmap('IT.ico')
root.geometry("800x400")
def missing():
while i < 100:
progress1['value'] = i
label1.config(text=progress1['value'])
root.update_idletasks()
i += 1
progress1 = ttk.Progressbar(root, orient=HORIZONTAL, length=250, mode='determinate')
progress1.pack(pady=15)
label1 = Label(root, text="")
label1.pack(pady=15)
button_1 = Button(root, text="Missing", command=missing)
button_1.pack(pady=15)
button_q = Button(root, text="Quit", command=root.destroy)
button_q.pack(pady=15)
root.mainloop()
so to update controls immediately, like updating labels and TreeView elements this code worked for me.
window = tk.Tk()
window.update_idletasks()