Hey im pretty new to python and im taking a class in high school. For an assignment im working on we have to make a tkinter gui that includes the widgets, label, buttons, entry box, radio or check buttons, frames, and a display box. I am making a kilometers to miles converter that can do the opposite if chosen, there will be radio buttons that the user can choose to choose which one they would like to calculate, but i am having a lot of trouble on the calculation part because i cant get the entry box number to multiple or divide by 1.609 or any number.
Heres the code i have now, I apologize for the mess and how bad it probably
import tkinter as tk
import tkinter.messagebox
# Customize main window
root = tk.Tk()
root.title('GUI Assignment')
# Create the frames, right, left, and bottom, and pack them
bframe = tk.LabelFrame(root, highlightthickness=0, borderwidth=0, padx=100, pady=50)
bframe.pack(side='bottom')
rframe = tk.LabelFrame(root, highlightthickness=0, borderwidth=0, padx=100, pady=50)
rframe.pack(side='right')
lframe = tk.LabelFrame(root, highlightthickness=0, borderwidth=0, padx=100, pady=50)
lframe.pack(side='left')
# Make the label and the entry box for the right frame
dlabel = tk.Label(rframe, text = 'Enter the distance', )
dentry = tk.Entry(rframe, width=75)
# Pack the label and entry
dlabel.pack(side='left')
dentry.pack(side="right")
dist = 3.0
temp =(dentry.get())
# Create the convert command
def convert():
if radio_var.get()==1:
tkinter.messagebox.showinfo('Distance',temp / dist )
# Make the convert and quit buttons
b = tk.Button(bframe, text="Convert", command=convert)
quit = tk.Button(bframe, text='Quit', command=root.destroy)
# Pack the buttons
b.pack(side='left')
quit.pack(side='right')
# Make the radio variable
radio_var = tk.IntVar()
radio_var.set(1)
# Make the radio buttons for the left frame
rb = tk.Radiobutton(lframe, text='Km to Miles', variable=radio_var, value=1)
rb2 = tk.Radiobutton(lframe, text='Miles to Km', variable=radio_var, value=2)
# Pack The Radio Buttons
rb.pack()
rb2.pack()
root.mainloop()
The issue you're having here is that you're trying to divide temp, a string, by dist, a float. You need to convert temp to a float before converting it using float(temp). Also, since you set temp once during your script, it will only ever refer to the value that was in the input box as soon as the variable was assigned. In order to fix this, you have to call dentry.get() inside of your convert() function rather than outside of it.
Related
I am trying to make a window that would show the location of the mouse at all times by using pyautogui and tkinter. I am new to tkinter and python overall so I am not quite sure how to make it so that the values would keep updating in the window, if it is even possible. Here is my code so far:
from tkinter import *
import pyautogui as pag
window = Tk()
window.geometry("200x200")
window.title("window")
window.config(background="#4ceefc")
coordinates = pag.position()
label1 = Label(window, text="mouse coordinates:")
label1.place(x=20, y=50)
label2 = Label(window, text=coordinates)
label2.place(x=30, y=90)
window.mainloop()
I tried using a while loop on the labels and window.mainloop() function but this did not work
Create a StringVar() to store the coords, and then assign it to the label's textvariable. You can then bind a '<Motion>' handler to your root window to update the label whenever the mouse moves.
coord_var = StringVar(window)
def on_mousemove(event):
coord_var.set(f'Mouse coordinates: {event.x}, {event.y}')
label1 = Label(window, textvariable=coord_var)
label1.place(x=20, y=50)
window.bind('<Motion>', on_mousemove)
Unless you're using pyautogui for something else, you can get away without it for this.
I have an application in which the images(created using Label(root,image='my_image)) change whenever some event occurs. Buttons are not used. One of my image has a label having text above an image. So it occurs where i want it. But when i move to next image after that, it is still there and i don't want it. What can i do? I have tried to destroy() the text label but it says that the variable is used before assignment.
Here is the part where i insert a text label. The panel2 variable doesn't work outside if block so i am not able to destroy it:
if common.dynamic_data:
to_be_displayed = common.dynamic_data
panel2 = tk.Label(root, text = to_be_displayed, font=("Arial 70 bold"), fg="white", bg="#9A70D4")
panel2.place(x=520,y=220)
You can do it on the canvas. Place label on the canvas and use bind functions for Enter and Leave events:
# imports
import tkinter as tk
# creating master
master = tk.Tk()
# hover functions
def motion_enter(event):
my_label.configure(fg='green')
print('mouse entered the canvas')
def motion_leave(event):
my_label.configure(fg='grey')
print('mouse left the canvas')
# create canvas, on which if you hover something happens
canvas = tk.Canvas(master, width=100, height=100, background='grey')
canvas.pack(expand=1, fill=tk.BOTH)
# create label
my_label = tk.Label(canvas, text='Toggle text is here!', fg='grey')
my_label.pack()
# binding enter and leave functions
master.bind('<Enter>', motion_enter)
master.bind('<Leave>', motion_leave)
# set window size
master.geometry('400x200')
# start main loop
master.mainloop()
You can change what configuration any objects have when you hovering canvas or anything else in created functions. Play with objects and code to do whatever you want to.
Also as it was mentioned you can store your labels or other objets in the list or dictionary to change separate objects, for exaple:
# imports
import tkinter as tk
# creating master
master = tk.Tk()
d = {}
# hover functions
def motion_enter(event):
d['first'].configure(fg='green')
print('mouse entered the canvas')
def motion_leave(event):
d['first'].configure(fg='grey')
print('mouse left the canvas')
# create canvas, on which if you hover something happens
canvas = tk.Canvas(master, width=100, height=100, background='grey')
canvas.pack(expand=1, fill=tk.BOTH)
# create label
my_label = tk.Label(canvas, text='Toggle text is here!', fg='grey')
my_label.pack()
d['first'] = my_label
my_label = tk.Label(canvas, text='Toggle text is here!', fg='grey')
my_label.pack()
d['second'] = my_label
# binding enter and leave functions
master.bind('<Enter>', motion_enter)
master.bind('<Leave>', motion_leave)
# set window size
master.geometry('400x200')
# start main loop
master.mainloop()
EDIT 1
If you want to remove label when the mouse left the canvas you can write such a functions:
def motion_enter(event):
d['first'].pack()
d['second'].pack()
print('mouse entered the canvas')
def motion_leave(event):
d['first'].pack_forget()
d['second'].pack_forget()
print('mouse left the canvas')
or just add 2 rows in the previous to combine them.
I have been doing some work in python and have came across Tkinter which is very useful for my project. I was in the process of making a screen where there is a button and a text entry box however when the text entry box is present, no button shows up. However when I remove the entry box, I can see the button.
Here is the part of the script I've been working on:
Hi, I have been doing some work in python and have came across Tkinter which is very useful for my project. I was in the process of making a screen where there is a button and a text entry box however when the text entry box is present, no button shows up. However when I remove the entry box, I can see the button.
from tkinter import *
def submit1():
print("working");
def password1():
passwordbox= Tk()
passwordbox.title("Password Verification")
passwordbox.configure(background="white")
passwordbox.geometry("1000x1000")
box1 = Entry(passwordbox, width=200, bg="gray")
box1.grid(row=2000, column=10, sticky=W)
submit = Button(passwordbox, text="Submit", width=20, height=5,
bg="black", fg="white", command=submit1)
submit.grid(row=1000, column=15, sticky=W);
password1()
The text box should show to entry box and the button however it only shows the button
If the entry box code was # out, the button will work
Anyone got any ideas?
You need to add a line passwordbox.mainloop() at the end of password1 definition. Also you need to specify row and column of the grid properly.
Set Entry box to row 0 and column 0
Set Submit button to row 1 and column 0
from tkinter import *
def submit1():
print("working");
def password1():
passwordbox= Tk()
passwordbox.title("Password Verification")
passwordbox.configure(background="white")
passwordbox.geometry("1000x1000")
box1 = Entry(passwordbox, width=200, bg="gray")
box1.grid(row=0, column=0, sticky=W)
submit = Button(passwordbox, text="Submit", width=20, height=5,
bg="black", fg="white", command=submit1)
submit.grid(row=1, column=0, sticky=W);
passwordbox.mainloop()
password1()
I am doing a GUI using for my code and finding it hard to develop what i want.
First ...
on the window an image and label appear and disappear after couple of seconds. after that a frame should arrive, followed by a menu option, when the menu option is selected it should disappear from frame and another image should appear.
self.gui = Tk()
def configure_window(self):
self.gui.geometry('700x500')
self.gui.resizable(height=False, width=False)
self.gui.update()
self.welcome_label()
self.welcome_image()
def welcome__image(self):
image = Image.open(image path)
photo = ImageTk.PhotoImage(image)
welcome_image = Label(master=self.gui, image=photo, justify='center',relief='raised')
welcome_image.image = photo
welcome_image.pack(padx=100, pady=100)
welcome_image.place(bordermode='outside', x=200,y=100)
welcome_image.after(ms=1000, func=welcome_image.place_forget)
def welcome_label(self):
welcome_label = Label(master=self.gui, text=welcome_label_text,font=welcome_label_font, justify='center',
state='active', fg='blue', anchor='center', pady=10, relief='raised' )
welcome_label.place(x=100, y=350)
welcome_label.after(ms=1000, func=welcome_label.place_forget)
def first_frame(self):
self.first_frame = LabelFrame( master = self.gui,text='Select First File',font= 'arial 10 bold underline', bg=self.background_colour,
height=200,width=690, bd=1, padx=5, pady=5)
self.first_frame.pack()
self.first_frame.place(x=0, y=0)
def select_button1(self):
self.file_open_button1 = Button(master=self.first_frame,text='...',state='disabled',command=self.cmd_file_select_button1)
when i run the code, welcome_image and welcome_frame places and forgets places after 1000 ms, but, first_frame also loads with parent widget. i want frame to arrive after the welcome_label disappears.
and the same sequence continues for LabelFrame
i have widgets in LabelFrame in which i have OptionMenu and button, i want optionMenu to disappear when user selects an option and another button should appear, same sequence in the button, button returns some sting and a label should appear in the place of button etc.
how to generate the sequence e.g. if an widget has place_forget() a sequence will be generated and another widget should be bind on that sequence. please help.
apology, if i am unable to make you understand my problem.
I would like a text box to ask for input in a tkinter window, then use that input as a parameter to call a function that draws a Sierpinski triangle. My buttons work but my input box does not. I keep trying to fix my code but it is not working, any help would be appreciated.
import tkinter as tk
from tkinter import *
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
root.title('Fractals') #titles the button box
top_frame = tk.Frame()
mid_frame = tk.Frame()
prompt_label = tk.Label(top_frame, \
text='Enter a number of iterations (more is better):')
iterations = tk.Entry(root,bd=1)
itr=iterations.get()
itr=int(itr)
button = tk.Button(frame,
text="QUIT",
fg="red",
command=quit)
button.pack(side=tk.LEFT)
sTriangle = tk.Button(frame,
text="Triangle",
command=lambda: sierpinski(fred, (-500,-500), (500,-500),
(0,500),itr))
sTriangle.pack(side=tk.LEFT)
fsquare = tk.Button(frame,
text="Square",
command=fractalsquare(fred,(-500,-500),(500,-500),
(500,500),(-500,500),itr))
fsquare.pack(side=tk.LEFT)
root.mainloop()
There are several issues:
1) Choose one way to import tkinter or confusion will result
2) You should provide a master for your Frames and then pack them. Pay attention on where the frames appear and what they contain.
3) It's usual to assign a textvariable to the Entry which will contain what you enter into it. The textvariable should be a tk.StringVar.
4) If a Button has a callback function, it must be defined before you create the button.
5) The variable fred is not defined.
Example of how you can write it:
import tkinter as tk
root = tk.Tk()
root.title('Fractals') #titles the button box
# Create the Label at the top
top_frame = tk.Frame(root) # Top Frame for
top_frame.pack()
prompt_label = tk.Label(top_frame,
text='Enter a number of iterations (more is better):')
prompt_label.pack()
# Create the Entry in the middle
mid_frame = tk.Frame(root)
mid_frame.pack()
itr_string = tk.StringVar()
iterations = tk.Entry(mid_frame,textvariable=itr_string)
iterations.pack()
fred=None # Was not defined...
# Create Buttons at the bottom
bot_frame = tk.Frame(root)
bot_frame.pack()
button = tk.Button(bot_frame, text="QUIT", fg="red", command=quit)
button.pack(side=tk.LEFT)
def sierpinski(*args): # sTriangle button callback function
itr = int(itr_string.get()) # How to get text from Entry
# if Entry does not contain an integer this will throw an exception
sTriangle = tk.Button(bot_frame, text="Triangle",
command=lambda: sierpinski(fred, (-500,-500), (500,-500),(0,500),itr_string))
sTriangle.pack(side=tk.LEFT)
def fractalsquare(*args): pass # fsquare button callback function
fsquare = tk.Button(bot_frame, text="Square", command=fractalsquare(fred,
(-500,-500),(500,-500),(500,500),(-500,500),itr_string))
fsquare.pack(side=tk.LEFT)
root.mainloop()
You should seriously study a basic tkinter tutorial. Try this one: An Introduction To Tkinter