Does anyone know why my tkinter buttons aren't rendering? - python

This is for a python project on GitHub where I'm making a GUI for a Magic 8 Ball simulation. I cant seem to use the .pack() function or my window just loads forever without ever instantiating.
When created
When I click a button the text appears
window = Tk()
window.configure(bg="black")
window.title("Magic 8 Ball")
Label(window, text="Ask the Magic 8 Ball the question on your mind or enter X to exit: ", bg="black", fg="white")\
.grid(row=0, column=0)
# Create entry box to type question
entrybox = Entry(window, width=30, bg="white")
entrybox.grid(row=1, column=0)
# Create output box at below buttons
output = Text(window, bg="white", fg="black", width=40, height=5)
output.grid(row=4, column=0)
# Create 4 button: Ask, Clear, Play Again, Quit
button_frame = Frame(window)
button_frame.configure(bg="black")
button_frame.grid(row=2, column=0)
#button_frame.pack(fill=X, side=BOTTOM)
Button(button_frame, text="Ask", width=10, bg="black", fg="white", command=click).grid(row=2, column=0)
Button(button_frame, text="Clear", width=10, command=clear).grid(row=2, column=1)
Button(button_frame, text="Play Again", width=10,command=repeat).grid(row=3, column=0)
Button(button_frame, text="Quit", width=10, command=close).grid(row=3, column=1)
window.mainloop()

I think we will need more specifications about your OS and python version. I ran it on Python 3.5.0 and Windows 10 with the result:
So I do not think it is an error in your code. I did have to add in all the functions and import you were missing so what I ran ended up looking like:
from tkinter import *
window = Tk()
def click():
print('click')
def clear():
print('clear')
def repeat():
print('repeat')
def close():
print('close')
window.configure(bg="black")
window.title("Magic 8 Ball")
Label(window, text="Ask the Magic 8 Ball the question on your mind or enter X to exit: ", bg="black", fg="white")\
.grid(row=0, column=0)
# Create entry box to type question
entrybox = Entry(window, width=30, bg="white")
entrybox.grid(row=1, column=0)
# Create output box at below buttons
output = Text(window, bg="white", fg="black", width=40, height=5)
output.grid(row=4, column=0)
# Create 4 button: Ask, Clear, Play Again, Quit
button_frame = Frame(window)
button_frame.configure(bg="black")
button_frame.grid(row=2, column=0)
#button_frame.pack(fill=X, side=BOTTOM)
Button(button_frame, text="Ask", width=10, bg="black", fg="white", command=click).grid(row=2, column=0)
Button(button_frame, text="Clear", width=10, command=clear).grid(row=2, column=1)
Button(button_frame, text="Play Again", width=10,command=repeat).grid(row=3, column=0)
Button(button_frame, text="Quit", width=10, command=close).grid(row=3, column=1)
window.mainloop()

Related

How to create a mandatory window in tkinter

I am using python 3.7 and tkinter for making a GUI which saves all my important passwords which are saved in a file passwords.txt. In this I want to create a button in my main window which pops up another window with an entry box and a button(which will close the window) and till this window is not closed it will not let the user to interact with my old window.
Here's my codes:
from tkinter import *
from tkinter import ttk
root = Tk()
f = open("passwords.txt", "r")
list1 = []
for item in f.readlines():
item = item.replace("\n", "")
list1.append(item)
def secondwindow():
root2 = Tk()
root2.title("Secure Your Password")
root2.configure(bg="black")
root2.geometry('700x600')
frame_color = "#%02x%02x%02x" % (150,150,150)
# Create A Main frame
main_frame = Frame(root2, bg=frame_color)
main_frame.pack(fill=BOTH,expand=1)
# Create Frame for X Scrollbar
sec = Frame(main_frame, bg=frame_color)
sec.pack(fill=X,side=BOTTOM)
# Create A Canvas
my_canvas = Canvas(main_frame, bg="black")
my_canvas.pack(side=LEFT,fill=BOTH,expand=1)
# Add A Scrollbars to Canvas
x_scrollbar = ttk.Scrollbar(sec,orient=HORIZONTAL,command=my_canvas.xview)
x_scrollbar.pack(side=BOTTOM,fill=X)
y_scrollbar = ttk.Scrollbar(main_frame,orient=VERTICAL,command=my_canvas.yview)
y_scrollbar.pack(side=RIGHT,fill=Y)
# Configure the canvas
my_canvas.configure(xscrollcommand=x_scrollbar.set)
my_canvas.configure(yscrollcommand=y_scrollbar.set)
my_canvas.bind("<Configure>",lambda e: my_canvas.config(scrollregion= my_canvas.bbox(ALL)))
# Create Another Frame INSIDE the Canvas
second_frame = Frame(my_canvas, bg=frame_color)
# Add that New Frame a Window In The Canvas
my_canvas.create_window((0,0),window=second_frame, anchor="nw")
f = Frame(second_frame, borderwidth=2, relief=SUNKEN, bg=frame_color)
f.pack(side=TOP, fill=X)
Label(f, text="Secure Your Password", fg="white", bg=frame_color, font="Algerian 35 italic").pack()
f1 = Frame(second_frame, bg="black")
f1.pack(fill=BOTH, side=TOP, expand=1)
Label(f1, text="Application", fg="red", bg="black", font="Calibri 20 bold", pady=10, padx=60).grid(row=1, column=1)
Label(f1, text="Username", fg="red", bg="black", font="Calibri 20 bold", pady=10, padx=210).grid(row=1, column=2)
Label(f1, text="Password", fg="red", bg="black", font="Calibri 20 bold", pady=10, padx=198).grid(row=1, column=3, padx=140)
for i in range(len(list1)):
application = list1[i].split(";;;")[0]
username = list1[i].split(";;;")[1]
password = list1[i].split(";;;")[2]
Label(f1, text=application, fg="white", bg="black", font="Calibri 20 bold", pady=5).grid(row=i+2, column=1)
Label(f1, text=username, fg="white", bg="black", font="Calibri 20 bold", pady=5).grid(row=i+2, column=2)
Label(f1, text=password, fg="white", bg="black", font="Calibri 20 bold", pady=5).grid(row=i+2, column=3)
root2.mainloop()
def checkPassword(password, l):
if password == "a":
root.destroy()
secondwindow()
else:
l.config(text="Wrong Password")
def password_window():
root.geometry('450x270')
root.title("Secure Your Password")
root.minsize(450, 270)
root.maxsize(450, 270)
root.configure(bg="black")
Label(root, text="Secure Your Password", fg="white", bg="black", font="Algerian 24 italic").pack(side=TOP)
Label(root, text="Your Password", fg="white", bg="black", font="Clibri 15").pack(pady=10)
password = StringVar()
Entry(root, textvariable=password, bg="grey", fg="white", font="Calibri 15 bold").pack(pady=10)
Button(root, text="Login", bg="grey", fg="white", activebackground="grey", font="Calibri 10", command=lambda: checkPassword(password.get(), l)).pack(pady=8)
l = Label(root, fg="red", bg="black", font="Clibri 10 bold")
l.pack()
password_window()
root.mainloop()
And my passwords.txt:
StackOverflow;;;PomoGranade;;;PomoGranade_StackOverflow
GitHub;;;Pomogranade;;;PomoGranade_GitHub
I am new to python and tkinter. Thanks for help in advance :)
I do not recommend using * imports, though it may not be exactly wrong in this case.
Use the TopLevel widget instead of initialising another Tk window. See why using another Tk is not good.
Use .grab_set() (Look at #TheLizzard's link in the comment for a better example)
Look at this example -
import tkinter as tk
root = tk.Tk()
def f1():
top1 = tk.Toplevel(root)
b2 = tk.Button(top1,text='Close New Window',command=top1.destroy)
b2.pack()
top1.grab_set()
b1 = tk.Button(root,text='Create Mandatory Window',command=f1)
b1.pack()
root.mainloop()
If you run this code, you will see that the first window does not react to any mouse press etc... and also you cannot close the first window after opening the new window until the it is closed

Why aren't my buttons properly aligned with python TKinter

I am creating a password manager which includes some buttons, but for some reason these buttons aren't aligning properly, could someone help out?
Here is the code i've done usint Tkinter for these buttons:
btn = Button(window, text="Exit Securely", command=exit)
btn.grid(column=2)
btn = Button(window, text="Add Entry", command=addEntry)
btn.grid(column=1)
btn = Button(window, text="Generate", command=run)
btn.grid(column=0)
lbl = Label(window, text="Website")
lbl.grid(row=3, column=0, padx=80)
lbl = Label(window, text="Username")
lbl.grid(row=3, column=1, padx=80)
lbl = Label(window, text="password")
lbl.grid(row=3, column=2, padx=80)
which makes my program look like this:
Any general tips or helpful links for how to make a nicer GUI would be appreciated as well, as I have been struggling with that.
As #acw1668 said if you don't specify row in grid(), it will take the next available row.
# Code to make this example work:
from tkinter import *
def addEntry():pass
def run():pass
window = Tk()
# Added `row=0` for each one of them
btn = Button(window, text="Exit Securely", command=exit)
btn.grid(row=0, column=2)
btn = Button(window, text="Add Entry", command=addEntry)
btn.grid(row=0, column=1)
btn = Button(window, text="Generate", command=run)
btn.grid(row=0, column=0)
# Changed the row to 1 for all of them
lbl = Label(window, text="Website")
lbl.grid(row=1, column=0, padx=80)
lbl = Label(window, text="Username")
lbl.grid(row=1, column=1, padx=80)
lbl = Label(window, text="password")
lbl.grid(row=1, column=2, padx=80)
By the way it is a good idea to use different names for the different buttons/labels.
I have been trying various method of aligning the widgets of tkinter in the program window lately and well I have found a better working solution to this.
In you program you have been using grid for aligning. I would say that you replace with place instead.
place will allow you to set a definite x and y coordinate for the widget and it would be easy to use.
If I alter your code accordingly, I can show you the code (after alteration) and the image of the output.
Code (After Alteration)
# Code to make this example work:
from tkinter import *
def addEntry():pass
def run():pass
window = Tk()
# Adding geometry ettig.
window.geometry('500x500')
btn = Button(window, text="Exit Securely", command=exit)
btn.place(x=410, y=20)
btn = Button(window, text="Add Entry", command=addEntry)
btn.place(x=210, y=20)
btn = Button(window, text="Generate", command=run)
btn.place(x=10, y=20)
lbl = Label(window, text="Website")
lbl.place(x=10, y=50)
lbl = Label(window, text="Username")
lbl.place(x=210, y=50)
lbl = Label(window, text="password")
lbl.place(x=410, y=50)
The Output Screen

Button Adjusting tkinter Python 3.8

all of my code is ready except the placement of the Quit button. I want to move to the Calculate button as much as possible, even like sticked to each other. Could you help in adjusting so the buttons will stick to each other?
from tkinter import *
window = Tk()
class MainGUI:
def __init__(self):
Label(window, text="Enter the property value: $").grid(row=1,column=1, sticky=W)
Label(window, text="Assessment Value").grid(row=2,column=1, sticky=W)
Label(window, text="Property Tax").grid(row=3,column=1, sticky=W)
self.propertyValue = StringVar()
self.assessmentValue = StringVar()
self.propertyTax = StringVar()
Entry(window, textvariable=self.propertyValue,justify=RIGHT).grid(row=1, column=2)
Button(window, text="Calculate",
command=self.calculate).grid(row=6, column=1, sticky=E)
Button(window, text="Quit",
command=self.close_window).grid(row=6, column=2, sticky=E)
Label(window, textvariable=
self.assessmentValue).grid(row=2, column=2, sticky=E)
Label(window, textvariable=
self.propertyTax).grid(row=3, column=2, sticky=E)
window.mainloop() # Create an event loop
def calculate(self):
self.assessmentValue.set("{0:10.2f}".format(float(self.propertyValue.get()) * 60 / 100))
self.propertyTax.set("{0:10.2f}".format(float(self.propertyValue.get()) * 60 / 10000 * 0.75))
def close_window(self):
window.destroy()
MainGUI()

Python Tkinter Entry() Calculations

I am currently trying to build a GUI calculator using python with the help of tkinter. I have managed to set up all of my buttons and they interact with my entry() bar when I press the button (e,g: Press button 5 and 5 appears into the entry()).
The only thing left to do is actually perform the mathematical equations that appear in the entry(). For example, if I enter 5 + 5 * 2 into the entry bar, how would I make the answer appear into the entry() after it's updated? So basically all I'm asking is someone to help me make this happen!
I have provided the code below and a screenshot of the calculator. Also please don't report this as a duplicate or flag this question as a post, (I'm reasking this question because I got no help on my last one so please help a young python programmer out!). Also I'm asking you not to provide me with links because I've read every possible link on tkinter there is to read and still have no clue what I'm doing.
Here is my code:
import sys
from tkinter import *
from PIL import Image, ImageTk
#ACTIONS:
def clear():
#Action: Clears the entry().
txtDisplay.delete(0,END);
return;
def update_Entry(inputValue):
#Updates the entry when a button is pressed.
currentText = num1.get();
update = num1.set(currentText + inputValue);
#Parent Window.
root = Tk();
root.title('Calculator ++ [1.7.2]');
root.geometry('350x450');
#Main entry.
num1 = StringVar();
txtDisplay = Entry(root, textvariable = num1, relief=RIDGE, bd = 10, width=33, insertwidth = 1, font = 40, justify=RIGHT);
txtDisplay.place(x=15, y=10);
txtDisplay.focus();
print(txtDisplay.get())
#Buttons:
zeroButton = Button(root, text='0', width=20, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('0'));
zeroButton.place(x=17,y=382);
oneButton = Button(root, text='1', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('1'));
oneButton.place(x=17, y=302);
twoButton = Button(root, text='2', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('2'));
twoButton.place(x=100, y=302);
threeButton = Button(root, text='3', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('3'));
threeButton.place(x=182, y=302);
fourButton = Button(root, text='4', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('4'));
fourButton.place(x=17, y=222);
fiveButton = Button(root, text='5', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('5'));
fiveButton.place(x=100, y=222);
sixButton = Button(root, text='6', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('6'));
sixButton.place(x=182, y=222);
sevenButton = Button(root, text='7', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('7'));
sevenButton.place(x=17, y=142);
eightButton = Button(root, text='8', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('8'));
eightButton.place(x=100, y=142);
ninthButton = Button(root, text='9', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('9'));
ninthButton.place(x=182, y=142);
decimalButton = Button(root, text='.', width=8, height=3, bg='powder blue', command=lambda:update_Entry('.'));
decimalButton.place(x=182, y=382);
equalButton = Button(root, text='=', width=8, height=8, bg='Lightgreen', command=lambda:update_Entry('='));
equalButton.place(x=264, y=307);
plusButton = Button(root, text='+', width=8, height=3, bg='gray', command=lambda:update_Entry('+'));
plusButton.place(x=264, y=222);
minusButton = Button(root, text='-', width=8, height=3, bg='gray', command=lambda:update_Entry('-'));
minusButton.place(x=264, y=142);
multiplyButton = Button(root, text='x', width=8, height=3, bg='gray', command=lambda:update_Entry('*'));
multiplyButton.place(x=264, y=66);
divideButton = Button(root, text='รท', width=8, height=3, bg='gray', command=lambda:update_Entry('/'));
divideButton.place(x=182, y=66);
clearButton = Button(root, text='Clear (CE)', width=20, height=3, command = clear, bg='Orange');
clearButton.place(x=17, y=66);
#Locks the parent windows size.
root.maxsize(350,450);
root.minsize(350,450);
#Parent window's background color:
root.configure(background = 'black');
root.mainloop();
Screenshot:
For something this simple, try having this as the command for your equalButton:
def evaluate():
currentText = num1.get()
try:
num1.set(str(eval(currentText)))
except SyntaxError:
num1.set('<ERROR>')

grid_remove on an Entry widget

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()

Categories