I'm pretty much a complete beginner when it comes to coding. I have been using python and the tkinter GUI to code a booking system. Eventually the database will need to be integrated but I'm trying to set up the GUI first. My code is a little messy but I'm not worried about that at the minute.
I'm try to get a button infront of the frame but it stays behind, any way of stopping this?
Here's my code for this...
def home_button():
home_title = Button(book, text='HOME', background='#DEEBF7', activebackground='#DEEBF7', width=15, border=0, font = ("Helvetica 15 italic"))
home_title.place(x=423, y=81)
def bookings_button():
bookings_title = Label(book, text='BOOKINGS', background='#DEEBF7', font = ("Helvetica 15 italic"))
bookings_title.place(x=475, y=85)
new_booking = Button(book, text='NEW BOOKING', width=20, height=2, background='#87B7E2')
new_booking.place(x=160, y=170)
def students_button():
students_title = Label(book, text='STUDENTS', background='#DEEBF7', font = ("Helvetica 15 italic"))
students_title.place(x=475, y=85)
## GUI ####
from tkinter import *
root = Tk()
#create the root window
book = Frame(root)
book.grid()
root.title("Home")
root.geometry("850x550")
root.configure(background='#DEEBF7')
backg = Button(book, height=850, width=550, background='#DEEBF7',
activebackground='#DEEBF7', border=0)
backg.pack()
#modify the windows size, colour and the size of the grid
logo1 = Button(book, width=175, height=117, border=0, background='#DEEBF7', activebackground='#DEEBF7', command=home_button)
logo = PhotoImage(file='Logo1.gif')
logo1.image = logo
logo1.configure(image=logo)
logo1.place(x=50, y=20)
title = Label(book, text = "GRAHAM'S SCHOOL OF MOTORING", background = '#DEEBF7', font = ("Helvetica 24 bold"))
title.place(x=250, y=40)
frame=Frame(root, width=551, height=384, background='#000000')
frame.place(x=250, y=135)
frame=Frame(root, width=547, height=380, background='#DEEBF7', borderwidth=5)
frame.place(x=252, y=137)
home = Button(book, text = "HOME", height=2, width=20, background='#5F85CD',
borderwidth=5, activebackground='#A2C7E8', relief='raised', command=home_button)
home.place(x=60, y=150)
bookings = Button(book, text="BOOKINGS", height=2, width=20, background='#5F85CD', borderwidth=5, activebackground='#A2C7E8', relief='raised', command=bookings_button)
bookings.place(x=60, y=235)
student = Button(book, text="STUDENTS", height=2, width=20, background='#5F85CD',
borderwidth=5, activebackground='#A2C7E8', relief='raised', command=students_button)
student.place(x=60, y=320)
back = Button(book, text="BACK", height=2, width=20, background='#FF5559',
borderwidth=5, activebackground='#BF230A', relief='raised')
back.place(x=45, y=450)
root.mainloop()
#kick off the window's event-loop
To put the button on top of the frame, I changed the master widget of the button:
I replaced
new_booking = Button(book, text='NEW BOOKING', width=20, height=2, background='#87B7E2')
by
new_booking = Button(root, text='NEW BOOKING', width=20, height=2, background='#87B7E2')
Related
Python TKinter Mac: Buttons layout strangely and when a button is clicked it looks the same (as if it hadn't been clicked) however I didn't check to see if the button worked.
and the space is a textbook
the Mac version is: a 2017 iMac running Monterey 12.4
import tkinter as tk
window = tk.Tk()
window.geometry("500x500")
window.title("Stock Watchlist & Logger")
label = tk.Label(window, text="Tester", font=('Ariel', 18))
label.pack(padx=20, pady=20)
textbox = tk.Text(window, height=3, font=('Ariel', 16))
textbox.pack(padx=10, pady=10)
numbuttframe = tk.Frame(window)
numbuttframe.columnconfigure(0, weight=1)
yesnobuttframe = tk.Frame(window)
yesnobuttframe.columnconfigure(1, weight=1)
button1 = tk.Button(numbuttframe, text="1", font=('Arial', 18))
button1.grid(row=0, column=0, sticky=tk.W+tk.E)
button2 = tk.Button(numbuttframe, text="2", font=('Arial', 18))
button2.grid(row=0, column=1, sticky=tk.W+tk.E)
button3 = tk.Button(numbuttframe, text="3", font=('Arial', 18))
button3.grid(row=0, column=2, sticky=tk.W+tk.E)
button4 = tk.Button(numbuttframe, text="4", font=('Arial', 18))
button4.grid(row=0, column=3, sticky=tk.W+tk.E)
button5 = tk.Button(numbuttframe, text="5", font=('Arial', 18))
button5.grid(row=0, column=4, sticky=tk.W+tk.E)
button6 = tk.Button(numbuttframe, text="6", font=('Arial', 18))
button6.grid(row=0, column=5, sticky=tk.W+tk.E)
yesbutton = tk.Button(yesnobuttframe, text="Yes", font=('Arial', 18))
yesbutton.grid(row=0, column=0, sticky=tk.W+tk.E)
nobutton = tk.Button(yesnobuttframe, text="No", font=('Arial', 18))
nobutton.grid(row=0, column=1, sticky=tk.W+tk.E)
numbuttframe.pack(fill='x')
yesnobuttframe.pack(fill='x')
if button1:
print("CELEBRATE!")
window.mainloop()
You set the weight to two cells weight=1 , so they expanded, since the rest have a default weight of 0. Since I don’t see your grid - the buttons are placed in frames one after the other, suggest using the pack method. And shortened your code a bit. The buttons won't work yet, because they don't have a command = call. Complex variable names in Python are usually written with an underscore.
import tkinter as tk
FONT = ('Ariel', 18)
window = tk.Tk()
window.geometry("500x500")
window.title("Stock Watchlist & Logger")
lbl = tk.Label(window, text="Tester", font=FONT)
lbl.pack(padx=20, pady=20)
text_box = tk.Text(window, height=3, font=('Ariel', 16))
text_box.pack(padx=10, pady=10)
num_btn = tk.Frame(window)
yes_no_btn = tk.Frame(window)
num_btn.pack(fill='x')
yes_no_btn.pack(fill='x')
buttons = []
for i in range(1, 7):
btn = tk.Button(num_btn, text=f"{i}", font=FONT)
btn.pack(side="left", fill='x', expand=True)
buttons.append(btn)
yes_btn = tk.Button(yes_no_btn, text="Yes", font=FONT)
yes_btn.pack(side="left", fill='x', expand=True)
no_btn = tk.Button(yes_no_btn, text="No", font=FONT)
no_btn.pack(side="left", fill='x', expand=True)
window.mainloop()
I have made a python gui using tkinter and i have been running it through the commandline. But when i tried to open it by double clicking, it shortly shows the window but exits again. I tried commenting out all the places where it uses images thinking that it is because it dosent have file-editing permissions when its run by double click and it worked! But i need to use images in the gui, anyone have solutions?
import tkinter as tk
from PIL import Image, ImageTk
import time
root = tk.Tk()
root.title("Krypto Coin")
root.iconbitmap('icon.ico')
root.configure(bg="#112233")
Frame = tk.Frame(root, width=1200, height=800, bg="#112233")
Frame.grid(columnspan=3, rowspan=5)
icon = Image.open('icon_round.png')
icon = ImageTk.PhotoImage(icon)
icon_label = tk.Label(image=icon, borderwidth=0, highlightthickness=0)
icon_label.place(relx=0.5, rely=0.2, anchor="center")
text = tk.Label(root, text="Welcome to Krypto Coin (KTC)", bg="#112233", fg="#ffffff", font=("Arial", 32))
text.place(relx=0.5, rely=0.45, anchor="center")
text = tk.Label(root, text="Enter id of the receiver and amount", bg="#112233", fg="#ffffff", font=("Arial", 24))
text.place(relx=0.5, rely=0.5, anchor="center")
def trasfer_button_pressed():
time.sleep(0.1)
trasfer_button_text.set("Loading...")
trasfer_button.configure(state="disable")
trasfer_button.configure(bg="#112233")
input_id.configure(state="disable")
input_amount.configure(state="disable")
def trasfer_button_enter(e):
if trasfer_button_text.get() == "Transfer":
trasfer_button.configure(bg="#334455")
def trasfer_button_leave(e):
if trasfer_button_text.get() == "Transfer":
trasfer_button.configure(bg="#223344")
trasfer_button_text = tk.StringVar()
trasfer_button = tk.Button(root, textvariable=trasfer_button_text, command=lambda:trasfer_button_pressed(), bg="#223344", fg="#ffffff", width=15, height=1, font=("Arial", 24), borderwidth=0, highlightthickness=0)
trasfer_button_text.set("Transfer")
trasfer_button.place(relx=0.5, rely=0.65, anchor="center")
trasfer_button.bind("<Enter>", trasfer_button_enter)
trasfer_button.bind("<Leave>", trasfer_button_leave)
input_id = tk.Entry(root, width=48, font = "Arial 14", bg="#334455", fg="#ffffff", borderwidth=0, highlightthickness=0)
input_id.insert(0, "ID")
input_id.place(relx=0.45, rely=0.8, anchor="center", height=30)
input_amount = tk.Entry(root, width=20, font = "Arial 14", bg="#334455", fg="#ffffff", borderwidth=0, highlightthickness=0)
input_amount.insert(0, "Amount")
input_amount.place(relx=0.65, rely=0.8, anchor="center", height=30)
root.mainloop()
Since some days I'll try to align these two items inside a Tkinter frame:
The pink part should be on the left and the green button on the right. With HtmlDivs and CSS a question of seconds, with TKinter a pain in the ...
Here is my python code:
import tkinter as tk
root = tk.Tk()
root.geometry("400x200")
buttons = tk.Frame(root)
buttons.pack(side="top", expand=True, fill='both')
label = tk.Label(buttons, text="Hello, world", anchor='w', background='pink')
b2 = tk.Button(buttons, text="EXIT", background='green')
label.grid(row=0, column=1, sticky='w', ipadx = '20', padx = '20')
b2.grid(row=0, column=3, sticky='e', ipadx = '20', padx = '20')
root.mainloop()
The final app will be running fullscreen on a 7" touch display.
The simplest solution is to use pack instead of grid, since you only have a single row of widgets inside of buttons. pack's strength is arranging things in a single row or a single column.
Just remove these two lines:
label.grid(row=0, column=1, sticky='w', ipadx = '20', padx = '20')
b2.grid(row=0, column=3, sticky='e', ipadx = '20', padx = '20')
... and replace them with this:
label.pack(side='left')
b2.pack(side='right')
Also, since you appear to be creating a toolbar, you want to leave expand as False and set fill to just "x", otherwise the toolbar will expand to fill the entire window:
buttons.pack(side="top", expand=False, fill='x')
Thx for your tips,
this is just a testcode to update my maincode.
Its not good to mix .pack and .grid, right ? If i do, the script crashes completely,
so ill have to re-do my mainscript i think.
This is what i need:
row: 1/2: label (it will be a real time clock) left 2/2: exit button (exit fullscreen) right
row: 1/3: image (weather), 2/3: weather data (label), 3/3: calendar
row: 4 buttons: 1. lightoff 2. light25%, 3.light50% 4.light100&
Thats it basically all is working, it just need to align it (im a coding hero g)
Since i have the frame from the code above, i thought i can easily add 2. & 3. row with another frames, but that does not seem to work ??
Preview:
https://i.stack.imgur.com/KzoqV.png
My (main)Code so far
root = Tk()
root.title('Model Definition')
root.config(background = "deepskyblue4")
root.attributes('-fullscreen',True)
root.bind('<Escape>',lambda e: root.destroy())
def currenttime():
string = strftime("%A, %d.%B.%Y %H:%M:%S")
lbl.config(text = string, background = 'deepskyblue4', fg='white', font=("colibri", 30))
lbl.after(1000, currenttime)
def light400():
FNULL = open(os.devnull, 'w')
subprocess.call(['gpio -g pwm 18 401'], stdout=FNULL, stderr=subprocess.STDOUT, shell=True)
def light425():
FNULL = open(os.devnull, 'w')
subprocess.call(['gpio -g pwm 18 425'], stdout=FNULL, stderr=subprocess.STDOUT, shell=True)
def light450():
FNULL = open(os.devnull, 'w')
subprocess.call(['gpio -g pwm 18 450'], stdout=FNULL, stderr=subprocess.STDOUT, shell=True)
def light475():
FNULL = open(os.devnull, 'w')
subprocess.call(['gpio -g pwm 18 500'], stdout=FNULL, stderr=subprocess.STDOUT, shell=True)
# Main frames
top_frame = Frame(root, bg='deepskyblue4', width=450, height=90, pady=3)
center = Frame(root, bg='deepskyblue2', width=50, height=40, padx=3, pady=3)
btm_frame = Frame(root, bg='deepskyblue4', width=450, height=20, pady=3)
btm_frame2 = Frame(root, bg='deepskyblue4', width=450, height=60, pady=3)
# layout all of the main containers
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(0, weight=1)
top_frame.grid(row=0, sticky="e", padx=(10, 0))
center.grid(row=1, sticky="nsew", pady=(10, 50))
btm_frame.grid(row=3, sticky="ew")
btm_frame2.grid(row=4, sticky="ew", padx=(10, 50))
# create the widgets for the top frame
lbl = Label(top_frame, background = 'deepskyblue4', anchor=W, justify=LEFT)
lbl.pack()
currenttime()
actionbutton = Button(top_frame, text="X", width=5, height=2, bg="deepskyblue4", fg="white", command=root.destroy)
hdr_left = Frame(top_frame, bg='deepskyblue4', width=100, height=190)
hdr_right = Frame(top_frame, bg='deepskyblue4', width=400, height=190, padx=3, pady=3)
# layout the widgets in the top frame
lbl.grid(row=0, column=1, sticky="w")
actionbutton.grid(row=0, column=2, sticky="e")
# create the center widgets
center.grid_rowconfigure(0, weight=1)
center.grid_columnconfigure(1, weight=1)
ctr_left = Frame(center, bg='deepskyblue2', width=100, height=190)
ctr_mid = Frame(center, bg='deepskyblue2', width=150, height=190, padx=3, pady=3)
ctr_right = Frame(center, bg='deepskyblue2', width=400, height=190, padx=3, pady=3)
ctr_left.grid(row=0, column=0, sticky="ns")
ctr_mid.grid(row=0, column=1, sticky="nsew")
ctr_right.grid(row=0, column=2, sticky="ns")
path = "icons/rain.png"
img = ImageTk.PhotoImage(Image.open(path))
panel = Label(ctr_left, image = img, bg="deepskyblue2")
panel.grid(row=0, columnspan=3)
#imgag = panel.pack(top_frame)
#CENTER ctr_mid
if x["cod"] != "404":
y = x["main"]
y2 = x["wind"]
currenttemp = y["temp"]
currentpressure = y["pressure"]
currenthumidiy = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
currentwind = y2["speed"]
label1 = Label(ctr_mid,text='Karlsruhe', font = ('calibri', 30), background = 'deepskyblue2')
label2 = Label(ctr_mid,text='Temperatur: '+str(round(currenttemp-272.15))+' °C', font = ('calibri', 20), background = 'deepskyblue2')
label3 = Label(ctr_mid,text='Beschreibung: '+str(weather_description),font = ('calibri', 20), background = 'deepskyblue2')
label4 = Label(ctr_mid,text='Druck: '+str(currentpressure)+' hPa', font = ('calibri', 20), background = 'deepskyblue2')
label5 = Label(ctr_mid,text='Feuchtigkeit: '+str(currenthumidiy)+' %',font = ('calibri', 20), background = 'deepskyblue2')
label6 = Label(ctr_mid,text='Wind: '+str(currentwind)+' m/Sek',font = ('calibri', 20), background = 'deepskyblue2')
label1.grid(row=0, column=0, sticky="nw")
label2.grid(row=1, column=0, sticky="nw")
label3.grid(row=2, column=0, sticky="nw")
label4.grid(row=3, column=0, sticky="nw")
label5.grid(row=4, column=0, sticky="nw")
label6.grid(row=5, column=0, sticky="nw")
# btm_frame2 widgets
licht = Label(btm_frame2, text='Licht:', width=5, height=1, bg="deepskyblue4", fg='white', font=("colibri", 20))
button = Button(btm_frame2, command=light400, text="AUS", width=5, height=1, bg="deepskyblue2", fg="white")
button2 = Button(btm_frame2, text="25 %", command=light425, width=5, height=1, bg="deepskyblue2", fg="white")
button3 = Button(btm_frame2, text="50%", command=light450, width=5, height=1, bg="deepskyblue2", fg="white")
button4 = Button(btm_frame2, text="100%", command=light475, width=5, height=1, bg="deepskyblue2", fg="white")
licht.grid(row=0, column=0, sticky="nw")
button.grid(row=0, column=1, sticky="nw")
button2.grid(row=0, column=2, sticky="nw")
button3.grid(row=0, column=3, sticky="nw")
button4.grid(row=0, column=4, sticky="nw")
actionbutton.grid(row=0, column=6, sticky="nw")
root.mainloop()
I'm trying to make this really simple GUI using tkinter and I'm using grid as a layout manager.
But when I place a certain button in column 2, it appears to the extreme left side of the window.
I just want to place the buttons exactly where I want in the window but that doesn't seem to work.
I don't know what I'm doing wrong exactly but here's the code and a screenshot.
from tkinter import *
class GUI:
#Initialize the application window
def __init__(self):
w = 520
h = 350
self.window = Tk()
ws = self.window.winfo_screenwidth()
hs = self.window.winfo_screenheight()
x = (ws/2) -(w/2)
y = (hs/2) -(h/2)
self.window.title("Excel file import")
self.window.geometry('%dx%d+%d+%d' % (w, h, x, y))
self.window.configure(bg='#004A99')
self.window.resizable(False,False)
# self.logo = Image.open(LOGO)
# self.log = self.logo.resize((150,105),Image.ANTIALIAS)
# self.logo2 = ImageTk.PhotoImage(self.log)
# self.lbl1 = Label(self.window, image=self.logo2)
# self.lbl1.image = self.logo2
# self.lbl1.grid(row=4, column=0, ipadx=0, ipady=0, pady=0, padx=0)
self.homeDirectory = r'C:/Users/Shtlrs/Desktop/Clients folder/'
self.cfgFile = self.homeDirectory + r'cfg.ini'
#Add client button
self.addClientBtn = Button(self.window, text="Add new client", bg='#1b98e0', fg="white",
width=20, height=1)
self.addClientBtn.grid(row=2, column=2, ipadx=5, ipady=5, pady=5, padx=5)
self.addClientBtn.bind("<ButtonRelease-1>",self.addNewClient)
#Select client button
self.selectClientBtn = Button(self.window, text="Select existing client", bg='#1b98e0', fg="white",
width=20, height=1)
self.selectClientBtn.grid(row=3, column=2, ipadx=5, ipady=5, pady=5, padx=5)
self.selectClientBtn.bind("<ButtonRelease-1>",self.selectClient)
# Delete client button
self.deleteClientBtn = Button(self.window, text="Delete existing client", bg='red', fg="white",
width=20, height=1)
self.deleteClientBtn.grid(row=4, column=2, ipadx=5, ipady=5, pady=5, padx=5)
self.deleteClientBtn.bind("<ButtonRelease-1>",self.deleteClient)
#Cients dropdown ( appears next to "select existing clients")
# clients = ["Medtronic","Ancora","Momo"]
# self.clientsDropDown = ttk.Combobox(self.window,values=clients)
# self.clientsDropDown.grid(row=3,column=1, ipadx=5,ipady=5,pady=5,padx=5)
# self.clientsDropDown.current(0)
self.restart = Button(self.window, text="Restart", bg='#1b98e0', fg="white",
width=20, height=1)
self.restart.grid(row=5, column=2, ipadx=5, ipady=5, pady=5, padx=5)
self.restart.bind("<ButtonRelease-1>", self.restartAPP)
self.window.mainloop()
The code lacks a lot of other functions of course (For the bindings)
But when I run this I get:
Buttons appear in the wrong column using tkinter's grid layout manager
Actually,it is the right position.Due to the first column has no widget,so it seems it is in the "wrong" column.
You can create a frame,and put all of your buttons in it.And use .pack(anchor=Center) or .pack(anchor="center") to make the frame in the center.Also,you need to set the bg attribute of Frame to make sure they have the same color.
Followed by your code,a minimal example code is here:
from tkinter import *
class GUI:
#Initialize the application window
def __init__(self):
w = 520
h = 350
self.window = Tk()
ws = self.window.winfo_screenwidth()
hs = self.window.winfo_screenheight()
x = (ws/2) -(w/2)
y = (hs/2) -(h/2)
self.window.title("Excel file import")
self.window.geometry('%dx%d+%d+%d' % (w, h, x, y))
self.window.configure(bg='#004A99')
self.window.resizable(False,False)
self.buttonFrame = Frame(self.window,bg="#004A99") # create a new frame
self.buttonFrame.pack(anchor=CENTER) # make it center
# self.logo = Image.open(LOGO)
# self.log = self.logo.resize((150,105),Image.ANTIALIAS)
# self.logo2 = ImageTk.PhotoImage(self.log)
# self.lbl1 = Label(self.window, image=self.logo2)
# self.lbl1.image = self.logo2
# self.lbl1.grid(row=4, column=0, ipadx=0, ipady=0, pady=0, padx=0)
self.homeDirectory = r'C:/Users/Shtlrs/Desktop/Clients folder/'
self.cfgFile = self.homeDirectory + r'cfg.ini'
#Add client button
self.addClientBtn = Button(self.buttonFrame, text="Add new client", bg='#1b98e0', fg="white",width=20, height=1) # put your button in the frame.
self.addClientBtn.grid(row=2, column=2, ipadx=5, ipady=5, pady=5, padx=5)
self.addClientBtn.bind("<ButtonRelease-1>",self.addNewClient)
#Select client button
self.selectClientBtn = Button(self.buttonFrame, text="Select existing client", bg='#1b98e0', fg="white",width=20, height=1) # put your button in the frame.
self.selectClientBtn.grid(row=3, column=2, ipadx=5, ipady=5, pady=5, padx=5)
self.selectClientBtn.bind("<ButtonRelease-1>",self.selectClient)
# Delete client button
self.deleteClientBtn = Button(self.buttonFrame, text="Delete existing client", bg='red', fg="white",width=20, height=1) # put your button in the frame.
self.deleteClientBtn.grid(row=4, column=2, ipadx=5, ipady=5, pady=5, padx=5)
self.deleteClientBtn.bind("<ButtonRelease-1>",self.deleteClient)
#Cients dropdown ( appears next to "select existing clients")
# clients = ["Medtronic","Ancora","Momo"]
# self.clientsDropDown = ttk.Combobox(self.buttonFrame,values=clients) # put it in the frame.
# self.clientsDropDown.grid(row=3,column=1, ipadx=5,ipady=5,pady=5,padx=5)
# self.clientsDropDown.current(0)
self.restart = Button(self.buttonFrame, text="Restart", bg='#1b98e0', fg="white",
width=20, height=1)
self.restart.grid(row=5, column=2, ipadx=5, ipady=5, pady=5, padx=5)
self.restart.bind("<ButtonRelease-1>", self.restartAPP)
self.window.mainloop()
#You need to revise all the functions below.
def addNewClient(self):
pass
def selectClient(self):
pass
def deleteClient(self):
pass
def restartAPP(self):
pass
start = GUI()
Now it is:
I am using Tkinter in python 3 and sqlite3 I create a registration form having two buttons and text label I am opening a new window after clicking on the sign in the button when I am creating another b\utton in signing window getting error
def new_winF():
newwin = Toplevel(root)
newwin.geometry('500x500')
# display = Label(newwin, width=70, height=80)
label_zero = Label(newwin, text="SignIn form", width=20, font=("bold", 20))
label_zero.place(x=90, y=63)
label_one = Label(newwin, text="Email", width=20, font=("bold", 10))
label_one.place(x=80, y=130)
label_one = Entry(newwin, textvar=Email)
label_one.place(x=240, y=130)
label_two = Label(newwin, text="Password", width=20, font=("bold", 10))
label_two.place(x=80, t=180)
label_two = Entry(newwin)
label_two.place(x=240, y=180)
buttonSignIn = Button(root, text="Sign in", width=10, bg='black', fg='white', command=new_winF).place(
x=140, y=430)
Perhaps that is due to error in line:
label_two.place(x=80, t=180)
Probably should be:
label_two.place(x=80, y=180)
As there is no option t in place() method.
https://www.tutorialspoint.com/python/tk_place.htm