Related
I am struggling ensure python script work on windows computer that does not have python installer. The script below only works on the computer with python software not sure where l am going wrong. Result is if uploaded on another computer no pictures or path is wrong. l am new to python can you please help as l dont know where l am going wrong. Thanks in advance
"""
from tkinter import*
import tkinter as tk
from tkinter import ttk
from datetime import datetime
windo = Tk()
windo.resizable(width=FALSE, height=FALSE)
windo.geometry("600x400")
windo.iconbitmap(r"C:\Users\breada\OneDrive\Desktop\Notes\image\Healthcare.ico")
house = "Mhungu"
def han():
print("Forms to be completed")
import tkinter as tk
from tkinter import ttk
from datetime import datetime
root = Tk()
root.resizable(width=FALSE, height=FALSE)
root.geometry("680x670")
root.iconbitmap(r"C:\Users\breada\OneDrive\Desktop\Notes\image\Healthcare.ico")
house = "Mhungu"
fun8 = Label(root, text="Running times comp :")
fun8.place(x=10,y=120)
var32 = IntVar()
chekbtn_1 = Checkbutton(root ,text="Yes", variable=var32)
chekbtn_1.place(x=180,y=120)
var33 = IntVar()
chekbtn_2 = Checkbutton(root ,text="No", variable=var33)
chekbtn_2.place(x=230,y=120)
def cli(value):
print("Severity of aggression")
print(value)
def clic(value):
print("Area of aggression")
print(value)
def click(value):
print("Nature of aggression")
print(value)
def save_funct():
print("Saved")
frame = LabelFrame(root, padx=5, pady=5)
v = tk.StringVar()
v.set("None")
lab2 = Label(frame, text="Select Level of Aggression", fg="blue", font=("Arial", 10))
lab2.pack()
radioButton1 = Radiobutton(frame, variable=v,value="1-No Concern", text="1-No Concern", command=lambda:cli(v.get()))
radioButton2 = Radiobutton(frame, variable=v, value="2-Not Severe",text="2-Not Severe",command=lambda:cli(v.get()) )
radioButton3 = Radiobutton(frame, variable=v, value="3-Slightly Severe",text="3-Slightly Severe",command=lambda:cli(v.get()) )
radioButton4 = Radiobutton(frame, variable=v, value="6-Extremely Severe",text="6-Extremely Severe",command=lambda:cli(v.get()) )
radioButton5 = Radiobutton(frame, variable=v,value="5-Severe", text="5-Severe", command=lambda:cli(v.get()))
radioButton6 = Radiobutton(frame, variable=v,value="4-Fairly Severe", text="6-Fairly Severe", command=lambda:cli(v.get()))
radioButton1.pack(side=LEFT)
radioButton2.pack(side=LEFT)
radioButton3.pack(side=LEFT)
radioButton4.pack(side=RIGHT)
radioButton5.pack(side=RIGHT)
radioButton6.pack(side=RIGHT)
frame.place(x=35, y=155)
frame1 = LabelFrame(root, padx=5, pady=5)
vv = tk.StringVar()
vv.set("None")
lab2 = Label(frame1, text="Areas of Aggressions", fg="blue", font=("Arial", 10))
lab2.pack()
radioButton1 = Radiobutton(frame1, variable=vv,value="Lounge", text="Lounge", command=lambda:clic(vv.get()))
radioButton2 = Radiobutton(frame1, variable=vv, value="Kitchen",text="Kitchen",command=lambda:clic(vv.get()) )
radioButton3 = Radiobutton(frame1, variable=vv, value="Bedroom 1",text="Bedroom 1",command=lambda:clic(vv.get()) )
radioButton4 = Radiobutton(frame1, variable=vv, value="Bedroom 2",text="Bedroom 2",command=lambda:clic(vv.get()) )
radioButton5 = Radiobutton(frame1, variable=vv,value="Bedroom 3", text="Bedroom 3", command=lambda:clic(vv.get()))
radioButton6 = Radiobutton(frame1, variable=vv,value="Dinning ", text="Dinning", command=lambda:clic(vv.get()))
radioButton1.pack(side=LEFT)
radioButton2.pack(side=LEFT)
radioButton3.pack(side=LEFT)
radioButton4.pack(side=RIGHT)
radioButton5.pack(side=RIGHT)
radioButton6.pack(side=RIGHT)
frame1.place(x=35, y=255)
frame2 = LabelFrame(root, padx=5, pady=5)
vvv = tk.StringVar()
vvv.set("None")
lab2 = Label(frame2, text="Nature of Aggression", fg="blue", font=("Arial", 10))
lab2.pack()
radioButton1 = Radiobutton(frame2, variable=vvv,value="Punching", text="Punching", command=lambda:click(vvv.get()))
radioButton2 = Radiobutton(frame2, variable=vvv, value="Kicking",text="Kicking",command=lambda:click(vvv.get()) )
radioButton3 = Radiobutton(frame2, variable=vvv, value="Pushing ",text="Pushing",command=lambda:click(vvv.get()) )
radioButton4 = Radiobutton(frame2, variable=vvv, value="Forceful",text="Forceful",command=lambda:click(vvv.get()) )
radioButton5 = Radiobutton(frame2, variable=vvv,value="Punching Walls", text="Punching Walls", command=lambda:click(vvv.get()))
radioButton6 = Radiobutton(frame2, variable=vvv,value="Clinch fists ", text="Clinch fists", command=lambda:click(vvv.get()))
radioButton1.pack(side=LEFT)
radioButton2.pack(side=LEFT)
radioButton3.pack(side=LEFT)
radioButton4.pack(side=RIGHT)
radioButton5.pack(side=RIGHT)
radioButton6.pack(side=RIGHT)
frame2.place(x=35, y=355)
buttnn = Button(root, text="Save", width=10, height=2, fg= "blue",command=save_funct)
buttnn.place(x=570, y=615)
root.mainloop()
def st_ii():
print("Redirected")
canvas=Canvas(width=400,height=200, bg="blue")
canvas.place(x=200,y=130)
photo=PhotoImage(file="C:\\Users\\breada\\OneDrive\\Desktop\\Forest.png")
canvas.create_image(0,0,image=photo, anchor=NW)
toolbar = Frame(windo, bg="powder blue", padx=3, pady=20)
insertButt= Button(toolbar,text = "A-Form",command =han)
insertButt.pack(side=LEFT, padx=6,pady=2)
shift_planButt = Button(toolbar, text= "B-Form",command =st_ii)
shift_planButt.pack(side=LEFT, padx=6,pady=2)
toolbar.pack(side=TOP,fill=X)
windo.mainloop()
"""
If you compile your script into an executable file, for example by using "auto-py-to-exe", then the resulting .exe-file can be run on any computer with the same architecture as the one you created the .exe file on.
You can include other files or folders containing pictures or icons using a simple GUI.
you can install it with pip:
$ pip install auto-py-to-exe
or directly from github:
https://github.com/brentvollebregt/auto-py-to-exe
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()
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()
First time here so forgive me as this is my FIRST attempt at making a silly GUI game (if you want to call it that). I'm trying to get the user to click a button and the image of their selection pops up. I can't seem to figure out how to get the image to pop up though.
Image does show if I run it separately.
My code:
from Tkinter import *
root = Tk()
class PokemonClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text="Welcome! Pick your Pokemon!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.CharButton = Button(root, text="Charmander", bg="RED", fg="White",
command=self.CharClick)
self.CharButton.pack(side=LEFT, fill=X)
self.SquirtButton = Button(root, text="Squirtle", bg="Blue", fg="White")
self.SquirtButton.pack(side=LEFT, fill=X)
self.BulbButton = Button(root, text="Bulbasaur", bg="Dark Green",
fg="White")
self.BulbButton.pack(side=LEFT, fill=X)
def CharClick(self):
print "You like Charmander!"
global CharSwitch
CharSwitch = 'Yes'
CharSwitch = 'No'
if CharSwitch == 'Yes':
CharPhoto = PhotoImage(file="Charmander.gif")
ChLabel = Label(root, image=CharPhoto)
ChLabel.pack()
k = PokemonClass(root)
root.mainloop()
This works, but the actual image no longer shows, if I keep the PhotoImage OUT of the class it will print but I want to have it print IF they click the specific button:
from Tkinter import *
root = Tk()
class PokemonClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text = "Welcome! Pick your Pokemon!", bg = "Black", fg = "White")
self.WelcomeLabel.pack(fill = X)
self.CharButton = Button(root, text = "Charmander", bg = "RED", fg = "White", command = CharClick)
self.CharButton.pack(side = LEFT, fill = X)
self.SquirtButton = Button(root, text = "Squirtle", bg = "Blue", fg = "White")
self.SquirtButton.pack(side = LEFT, fill = X)
self.BulbButton = Button(root, text = "Bulbasaur", bg = "Dark Green", fg = "White")
self.BulbButton.pack(side = LEFT, fill = X)
def CharClick():
print "You like Charmander!"
CharPhoto = PhotoImage(file = "Charmander.gif")
ChLabel = Label(root, image = CharPhoto)
ChLabel.pack()
k = PokemonClass(root)
root.mainloop()
You need to maintain a reference to your PhotoImage object. Unfortunately there is an inconsistency in tkinter in that attaching a Button to a parent widget increments the reference count, but adding an image to a widget does not increment the reference count. As a consequence at the moment the CharPhoto variable goes out of scope at the end of the function CharClick, the number of reference to the PhotoImage falls to zero and the object is made available for garbage collection.
If you keep a reference to the image somewhere, it will appear. When you kept it globally it remained in scope for the entire script and hence appeared.
You can keep a reference to it in the PokemonClass object or in the Label widget.
Below is the later of those options
from Tkinter import *
root = Tk()
class PokemonClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text="Welcome! Pick your Pokemon!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.CharButton = Button(root, text="Charmander", bg="RED", fg="White",
command=self.CharClick)
self.CharButton.pack(side=LEFT, fill=X)
self.SquirtButton = Button(root, text="Squirtle", bg="Blue", fg="White")
self.SquirtButton.pack(side=LEFT, fill=X)
self.BulbButton = Button(root, text="Bulbasaur", bg="Dark Green",
fg="White")
self.BulbButton.pack(side=LEFT, fill=X)
def CharClick(self):
print "You like Charmander!"
global CharSwitch
CharSwitch = 'Yes'
CharPhoto = PhotoImage(file="Charmander.gif")
ChLabel = Label(root, image=CharPhoto)
ChLabel.img = CharPhoto
ChLabel.pack()
CharSwitch = 'No'
k = PokemonClass(root)
root.mainloop()
The solution which helped me is just simply declaring all the image variables on the next line after 'root = Tk()'. Doing so won't spoil your code or anything.
Python noob here. I've created a simple tkinter app with 6 frames. Using multiple frames was the easiest way I could find to get all of the widgets to line up.
I want to have a text entry field in one of the frames that can be updated by other functions in the code. However, no matter what I try, I cannot get blah.set( "blah" ) to work.
I'm not using the self/parent stuff because I have not been able to figure that out yet. Here's what I've got:
def Next () :
glob_current_company_display.set( "test" )
def makeWindow () :
win = Tk()
win.title('Finder')
win.geometry('+842+721')
# ************************************************************************
# Frame 2
frame2 = Frame(win)
button_03 = Button(frame2, text="Next", width=10, command=Next)
button_03.pack(side=LEFT)
# ************************************************************************
# Frame 5
frame5 = Frame(win)
co_name_label = Label(frame5, text="Company Name: ", justify=LEFT)
co_name_label.pack(side=LEFT)
global glob_current_company_display
glob_current_company_display = StringVar()
co_name_entry = Entry(frame5, width=50, textvariable=glob_current_company_display)
co_name_entry.pack(side=LEFT)
# ************************************************************************
# Pack the frames
frame5.pack(side=TOP, pady=5, padx=5)
frame2.pack(side=TOP, pady=5, padx=5)
return win
win = makeWindow()
win.mainloop()
You probably should investigate the "self/parent stuff". It's comes in very handy for this kind of stuff. For now: you could put the creation of the global variable before the button_03 that has Next() as command (which has a reference to te global in it).
from Tkinter import *
def Next () :
glob_current_company_display.set( "test" )
def makeWindow () :
win = Tk()
win.title('Finder')
win.geometry('+842+721')
global glob_current_company_display
glob_current_company_display = StringVar()
# ************************************************************************
# Frame 2
frame2 = Frame(win)
button_03 = Button(frame2, text="Next", width=10, command=Next)
button_03.pack(side=LEFT)
# ************************************************************************
# Frame 5
frame5 = Frame(win)
co_name_label = Label(frame5, text="Company Name: ", justify=LEFT)
co_name_label.pack(side=LEFT)
co_name_entry = Entry(frame5, width=50, textvariable=glob_current_company_display)
co_name_entry.pack(side=LEFT)
# ************************************************************************
# Pack the frames
frame5.pack(side=TOP, pady=5, padx=5)
frame2.pack(side=TOP, pady=5, padx=5)
return win
win = makeWindow()
win.mainloop()