import tkinter
app = tkinter.Tk()
app.geometry("1080x2400")
title = tkinter.Label(
app, text="contador de sets y descansos", font=("Arial", 30))
title.pack(side=tkinter.TOP, fill=tkinter.BOTH)
design = tkinter.Label(app, bg="white")
design.pack(fill=tkinter.BOTH, expand=True)
def series():
label = tkinter.Label(sets, text="completed a set")
label.pack()
sets = tkinter.Button(design, text="sets", padx=40,
pady=20, font=("Arial", 20), command=series)
sets.pack(side=tkinter.LEFT)
def descanso():
label = tkinter.Label(rest, text="completed rest")
label.pack()
rest = tkinter.Button(design, text="rest", padx=40,
pady=20, font=("Arial", 20), command=descanso)
rest.pack(side=tkinter.RIGHT,)
app.mainloop()
I tried to make a button that displays a message on the GUI, but when I press it, the button disappears and what I want is the button to display the message and stay there
Use app for all in line 17, 21, 27 and 31. You had this Button(design,. Should be Button(app,
Here is code:
import tkinter
app = tkinter.Tk()
app.geometry("1080x2400")
title = tkinter.Label(
app, text="contador de sets y descansos", font=("Arial", 30))
title.pack(side=tkinter.TOP, fill=tkinter.BOTH)
design = tkinter.Label(app, bg="white")
design.pack(fill=tkinter.BOTH, expand=True)
def series():
label = tkinter.Label(app, text="completed a set")
label.pack()
sets = tkinter.Button(app, text="sets", padx=40,
pady=20, font=("Arial", 20), command=series)
sets.pack(side=tkinter.LEFT)
def descanso():
label = tkinter.Label(app, text="completed rest")
label.pack()
rest = tkinter.Button(app, text="rest", padx=40,
pady=20, font=("Arial", 20), command=descanso)
rest.pack(side=tkinter.RIGHT,)
app.mainloop()
Output:
Related
When I press OK to print out the answer multiple times, the answers just stack on each other but are not replaced by each other, how do I fix this bug?
from tkinter import *
from tkinter import messagebox
def main():
global window
window = Tk()
window.title("Calculator")
window.geometry("540x540")
label1 = Label(window, text="Calculator", font=("Windsor", 30), fg="light blue")
label1.pack()
global entry1
entry1 = Entry(window, width=20, font=("Arial 20"))
entry1.pack()
entry1.focus()
label2 = Label(window, text="+", font=("Windsor", 30), fg="light blue")
label2.pack()
global entry2
entry2 = Entry(window, width=20, font=("Arial 20"))
entry2.pack()
entry2.focus()
global label3
label3 = Label(window, text="=", font=("Windsor", 30), fg="light blue")
label3.pack()
button2 = Button(window, text="OK", fg="blue",
font="Arial 16 bold", command =button2_click)
button2.pack()
window.mainloop()
def button2_click():
Label.after(0, label.master.destroy)
try:
a = int(entry1.get())
b = int(entry2.get())
Label(window, text=f"{a+b}", font=("Windsor", 30), fg="light blue").pack()
except:
messagebox.showwarning("Error", "Invalid Entry or Entry Missing!")
if __name__=='__main__':
main()
It is better to create the result label once inside main() and update its text inside button2_click():
from tkinter import *
from tkinter import messagebox
def main():
global entry1, entry2, result
window = Tk()
window.title("Calculator")
window.geometry("540x540")
label1 = Label(window, text="Calculator", font=("Windsor", 30), fg="light blue")
label1.pack()
entry1 = Entry(window, width=20, font=("Arial 20"))
entry1.pack()
entry1.focus()
label2 = Label(window, text="+", font=("Windsor", 30), fg="light blue")
label2.pack()
entry2 = Entry(window, width=20, font=("Arial 20"))
entry2.pack()
label3 = Label(window, text="=", font=("Windsor", 30), fg="light blue")
label3.pack()
# create result label
result = Label(window, font=("Windsor", 30), fg="light blue")
result.pack()
button2 = Button(window, text="OK", fg="blue", font="Arial 16 bold", command=button2_click)
button2.pack()
window.mainloop()
def button2_click():
# below line will raise exception
#Label.after(0, label.master.destroy)
try:
a = int(entry1.get())
b = int(entry2.get())
# update result label
result.config(text=f"{a+b}")
except:
messagebox.showwarning("Error", "Invalid Entry or Entry Missing!")
if __name__=='__main__':
main()
Edit: I moved the button2_click () to the top. I comment out in line 17.
from tkinter import *
from tkinter import messagebox
window = Tk()
window = Tk()
def main():
global window
window.title("Calculator")
window.geometry("540x540")
label1 = Label(window, text="Calculator", font=("Windsor", 30), fg="light blue")
label1.pack()
def button2_click():
Label.after(0, label.master.destroy)
try:
a = int(entry1.get())
b = int(entry2.get())
Label(window, text=f"{a+b}", font=("Windsor", 30), fg="light blue").pack()
except:
messagebox.showwarning("Error", "Invalid Entry or Entry Missing!")
global entry1
entry1 = Entry(window, width=20, font=("Arial 20"))
entry1.pack(ipadx =10, ipady= 10)
entry1.focus()
label2 = Label(window, text="+", font=("Windsor", 30), fg="light blue")
label2.pack()
global entry2
entry2 = Entry(window, width=20, font=("Arial 20"))
entry2.pack()
entry2.focus()
global label3
label3 = Label(window, text="=", font=("Windsor", 30), fg="light blue")
label3.pack(ipadx =20, ipady= 20)
button2 = Button(window, text="OK", fg="blue",
font="Arial 16 bold", command =button2_click)
button2.pack()
window.mainloop()
def button2_click():
Label.after(0, label.master.destroy)
try:
a = int(entry1.get())
b = int(entry2.get())
Label(window, text=f"{a+b}", font=("Windsor", 30), fg="light blue").pack()
except:
messagebox.showwarning("Error", "Invalid Entry or Entry Missing!")
if __name__=='__main__':
main()
im working on this tkinter project im close to finishing but i cant seem to find a way to change the button color when i hover on it so can you help here is my code
import tkinter as tk
window = tk.Tk()
img = tk.PhotoImage(file='C:\\Users\\laithmaree\\PycharmProjects\\create_apps_with_python\\brainicon.ico.png')
window.title("Quiz Game")
# 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()
lblcorrect.after(1000, 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)
playbtn = tk.Button(window, text='Play', font=("Arial Bold", 90), bg='red', command=playbuttonclicked)
playbtn.place(x=10, y=200)
def quitbuttonclicked():
window.destroy()
quitbtn = tk.Button(window, text='Quit', font=("Arial Bold", 90), bg='red', command=quitbuttonclicked)
quitbtn.place(x=400, y=200)
window.mainloop()
the buttons are submitbtn,playbtn,quitbtn i want the hover over buttons to be black there already red i just want them to be black when i hover over them thx
Bind each of the buttons to entering and leaving events (when mouse enters and leaves the widget) and based on which one is triggered, change the background color of the button:
btn.bind('<Enter>', lambda e: e.widget.config(bg='black'))
btn.bind('<Leave>', lambda e: e.widget.config(bg='red'))
I am working on a simple counter app in tkinter. I rigged up some code looking at few tutorial on web. All the functions of a counter are set up. But when it comes to the designing of the app, I want the Count, the Count button, and the reset button to be aligned at the center.
The code is as below
from tkinter import Label, Button, Tk
from tkinter import font
window = Tk()
window.geometry('500x500')
window.title("Counter")
window.count = 0
def increment():
window.count += 1
lbl.configure(text=window.count)
def reset():
window.count = 0
lbl.configure(text=window.count)
lbl = Label(window, text="0", font=("Apple Braille", 60))
lbl.grid(column=0, row=0)
btn1 = Button(window, text="Count", command=increment)
btn1.grid(column=0, row=1)
btn2 = Button(window, text="Reset", command=reset)
btn2.grid(column=1, row=1)
btn1['font'] = btn2['font'] = font.Font(size=30)
window.mainloop()
A Screenshot of my counter app is here
Any help in this aspect will be appreciated.
Thanks,
It is easier to use pack() instead of grid() for your requirement.
lbl = Label(window, text="0", font=("Apple Braille", 60))
lbl.pack()
# frame for the two buttons
frame = Frame(window)
frame.pack()
btn1 = Button(frame, text="Count", command=increment)
btn1.grid(column=0, row=1)
btn2 = Button(frame, text="Reset", command=reset)
btn2.grid(column=1, row=1)
If you want to put at the center of the window:
# frame for the label and buttons
frame = Frame(window)
frame.place(relx=0.5, rely=0.5, anchor="c") # put at center of window
lbl = Label(frame, text="0", font=("Apple Braille", 60))
lbl.grid(row=0, column=0, columnspan=2)
btn1 = Button(frame, text="Count", command=increment)
btn1.grid(column=0, row=1)
btn2 = Button(frame, text="Reset", command=reset)
btn2.grid(column=1, row=1)
Very simple, don't be impressed by the size of the code.
I want to do something very simple (well, not for me, since I'm asking for help here) put the location of the open file in the red square on the screen:
Screen
import tkinter as tk
from tkinter.filedialog import askopenfilename
from tkinter import messagebox
def OpenFile_AntiDuplicate():
global antiduplicate_file
mainframe = tk.Frame(bg='#1c2028')
antiduplicate_file = askopenfilename(initialdir="/",
filetypes =(("Text file", "*.txt"),("All files","*.*")),
title = "Open text file"
)
fichier_dir = tk.Label(mainframe, text=antiduplicate_file).pack()
try:
with open(antiduplicate_file,'r') as UseFile:
print(antiduplicate_file)
except:
print("Non-existent file")
def RUN_AntiDuplicate():
try:
with open(antiduplicate_file,'r') as UseFile:
print(antiduplicate_file)
except:
error1 = tk.messagebox.showerror("ERROR", "No files exist!")
#----------------------------------------------------------
class HoverButton(tk.Button):
def __init__(self, master, **kw):
tk.Button.__init__(self,master=master,**kw)
self.defaultBackground = self["background"]
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
def on_enter(self, e):
self['background'] = self['activebackground']
def on_leave(self, e):
self['background'] = self.defaultBackground
#----------------------------------------------------------
def Anti_Duplicate():
mainframe = tk.Frame(bg='#1c2028')
mainframe.grid(row=0, column=0, sticky='nsew')
bouton_1 = HoverButton(mainframe, font=("Arial", 10), text="Back",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#CF3411',
relief='ridge', command=mainframe.destroy)
bouton_1.place(x=520, y=300)
open_button = HoverButton(mainframe, font=("Arial", 10), text="Open File..",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf',
relief='ridge', command = OpenFile_AntiDuplicate)
open_button.place(x=284.3, y=200, anchor='n')
run_button = HoverButton(mainframe, font=("Arial", 20), text="RUN",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#11CF6D',
relief='ridge', command = RUN_AntiDuplicate)
run_button.place(x=50, y=330, anchor='s')
bouton_2 = tk.Button(mainframe, font=("Arial", 10),
text="The purpose of this tool is to remove duplicate lines from a text file.",
background='#202124', fg='#1195cf', borderwidth=2,
activebackground= '#202124', activeforeground='#1195cf', relief='sunken')
bouton_2.place(relx=.5, y=50, anchor='n')
bouton_1 = tk.Button(mainframe, font=("Arial", 15), text="Anti-Duplicate",
background='#202124', fg='#1195cf', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf', relief='sunken')
bouton_1.pack(side= "top", padx= 5, pady=5, ipadx= 30, anchor="n")
#----------------------------------------------------------
def main_menu():
root = tk.Tk()
screenn_x = int(root.winfo_screenwidth())
root.config(background='#1c2028')
screenn_y = int(root.winfo_screenheight())
root.title("ComboKit v0.0.1")
root.minsize(570, 340)
root.resizable(0,0)
windowss_x = 570
windowss_y = 340
possX = (screenn_x // 2) - (windowss_x // 2)
possY = (screenn_y // 2) - (windowss_y // 2)
geoo = "{}x{}+{}+{}".format(windowss_x, windowss_y, possX, possY)
root.geometry(geoo)
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
mainframe = tk.Frame(root, bg='#1c2028')
mainframe.grid(row=0, column=0, sticky='n')
main_fusion_bouton = HoverButton(mainframe, font=("Arial", 15), text="Fusion",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf',
relief='ridge', command=None)
main_fusion_bouton.pack(side= "left", padx= 5, pady=5, ipadx= 10, anchor="n")
main_antiduplicate_bouton = HoverButton(mainframe, font=("Arial", 15), text="Anti-Duplicate",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf',
relief='ridge', command=Anti_Duplicate)
main_antiduplicate_bouton.pack(side= "left", padx= 5, pady=5, ipadx= 30)
main_split_button = HoverButton(mainframe, font=("Arial", 15), text="Split",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf',
relief='ridge', command=None)
main_split_button.pack(side= "left", padx= 5, pady=5, ipadx= 19, anchor="n")
root.mainloop()
main_menu()
So here's my code allows you to use 3 tools:
"Split" / "Anti-Duplicate" / "Merge"
At the moment I'm working on the "Anti-Duplicate" so it's on this Frame() where the text should be displayed.
I've already done everything, even the button to open the file explorer, but for the moment the location of the file is only displayed in the cmd.
Thank you very much!
The location of the file does not show up because you created a new frame to hold the label fichier_dir inside OpenFile_AntiDuplicate() and you did not call any layout function on the frame, so the frame will not be shown.
Better create the label fichier_dir inside Anti_Duplicate() and pass it to OpenFile_AntiDuplicate() function:
def Anti_Duplicate():
...
fichier_dir = tk.Label(mainframe, bg='#1c2028', fg='white')
fichier_dir.place(relx=0.5, y=170, anchor='n')
open_button = HoverButton(mainframe, font=("Arial", 10), text="Open File..",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf',
relief='ridge', command = lambda: OpenFile_AntiDuplicate(fichier_dir))
...
And update OpenFile_AntiDuplicate(...):
def OpenFile_AntiDuplicate(fichier_dir):
global antiduplicate_file
antiduplicate_file = askopenfilename(initialdir="/",
filetypes =(("Text file", "*.txt"),("All files","*.*")),
title = "Open text file"
)
fichier_dir['text'] = antiduplicate_file
...
Im new to Tkinter and am trying to build a simple GUI using grid manager which upon the push of button1, button2 appears along with an adjacent entry box. If you then press button2 the entry box and button2 dissapear. Below is a slice from the GUI code, the button dissapears but the entry box does not:
import Tkinter
from Tkinter import *
master = Tk()
CreateTestButton = Button(master, text="Create Test", command = CreateTest, fg="red", bg="white", font="Helvetica 10 bold")
CreateTestButton.grid(column=7, row=1)
def CreateTest():
TestEntry = Entry(master, text="", width = 100).grid(row=4,columnspan=6)
Label(self, text="Enter Test Name:").grid(row=3, column=0)
SaveTestButton = Button(master, text="Save to database", command=saveTest, fg="green", bg="white", font="Helvetica 10 bold")
SaveTestButton.grid(row=4, column=5)
def saveTest():
SaveTestButton.grid_remove()
TestEntry.grid_remove() #ERROR
mainloop()
How is one to remove entry boxes using grid manager in Tkinter? And other widgets for that matter I will also be needing to remove a list box, labels and widgets uppon a button click or event.
Regards,
Daniel
grid return nothing; By executing TestEntry = Entry(..).grid(...), TestEntry become None instead of Entry object.
Replace following line:
TestEntry = Entry(self, text="", width = 100).grid(row=4,columnspan=6)
with:
TestEntry = Entry(self, text="", width = 100)
TestEntry.grid(row=4,columnspan=6)
Complete code
from Tkinter import *
def CreateTest():
def saveTest():
SaveTestButton.grid_remove()
TestEntry.grid_remove() #ERROR
TestEntry = Entry(master, text="", width = 100)
TestEntry.grid(row=4,columnspan=6)
Label(master, text="Enter Test Name:").grid(row=3, column=0)
SaveTestButton = Button(master, text="Save to database", command=saveTest, fg="green", bg="white", font="Helvetica 10 bold")
SaveTestButton.grid(row=4, column=5)
master = Tk()
CreateTestButton = Button(master, text="Create Test", command = CreateTest, fg="red", bg="white", font="Helvetica 10 bold")
CreateTestButton.grid(column=7, row=1)
mainloop()