How do I set a maximum value in Tkinter? - python

I made an application in Tkinter and I want the user to be able to change the canvas size. When I click the button on the root it should open up a dialog that changes the size of the canvas. I also want to add a maximum value, so the user cant pick a width of more than 1300 and a height of 660.
Here is my code:
from tkinter import *
root = Tk()
root.geometry("10000x10000")
canvas = Canvas().pack()
button = Button(root, text="Change Canvas Size").pack()
def changeCanvasSize():
root2 = Toplevel(root)
root2.title("Change the canvas Size")
widthText = Label(root2, text="Canvas Width").pack()
changeCanvasWidth = Entry(root2).pack()
changeCanvasWidth.insert(0, "1100")
heightText = Label(root2, text="Change Canvas Height").pack()
changeCanvasHeight = Entry(root2).pack()
changeCanvasHeight.insert(0, "566")
applySizes = Button(root2, text="Apply", command = lambda: canvas.configure(width=changeCanvasWidth.get(), height=changeCanvasHeight.get()))
root.mainloop()
So how would I set a maximum value, width should be 1300 or less and height should be 600 or less. How would I do that?

why dont you use a if statement? and create a pop-up error message `
if changeWidth.get() > 1300:
newLabel = tk.Label(text="Enter Number Less 1300")

Related

How do I get the width of the taskbar without using win32api? Python 3.7

I'm having a problem where I'm trying to set my window height to full screen but I also want to use .overrideredirect(True), but doing this makes the window also cover the taskbar. So I've decided to get the width of the taskbar and subtract it from the width of the entire screen and use that as the width of the screen.
Everything that I could find about this problem included win32api, but win32api doesn't work on my version of python 3.7 or higher. I'm also using pyautogui to get the full screen resolution.
Here is my code:
import pyautogui
import customtkinter
customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("dark-blue")
root = customtkinter.CTk()
root.title('custom title bar')
# Get full screen resolution
print(pyautogui.size())
winSize = pyautogui.size()
# Convert it to a string
winSizeStr = str(winSize)
# Split it to width and height
WinX, WinY = winSizeStr.split(' ', 1)
# Removing the extra
winXstr = WinX.replace("Size(width=", "")
winYstr = WinY.replace("height=", "")
winXstrGeo = winXstr.replace(",", "")
winYstrGeo = winYstr.replace(")", "")
# Print the width and height
print(winXstrGeo)
print(winYstrGeo)
# Use the width and height in the window width and height and spawn the window at 0,0 of the screen
root.geometry(f"{winXstrGeo}x{winYstrGeo}+0+0")
# Remove Title Bar
root.overrideredirect(True)
# Create Fake Title Bar
title_bar = customtkinter.CTkFrame(master=root, corner_radius=0)
title_bar.pack()
# Titlebar name
title_label = customtkinter.CTkLabel(master=title_bar, text="custom title bar", width=1633)
title_label.pack(pady=2, padx=0, side='left')
# Close button
close = customtkinter.CTkButton(master=root, text="X", fg_color="#202020", hover_color="#ff1c1c", width=30, corner_radius=0, command=root.quit)
close.pack(pady=0, padx=0, side='right')
root.mainloop()
Thanks in advance :D
I have tested this code with Python 3.11.1 and 3.7.9:
import customtkinter
import ctypes
customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("dark-blue")
root = customtkinter.CTk()
root.title('custom title bar')
screen_height = root.winfo_screenheight() - ctypes.windll.user32.GetSystemMetrics(48)
# Use the width and height in the window width and height and spawn the window at 0,0 of the screen
root.geometry(f"{root.winfo_screenwidth()}x{screen_height}+0+0")
# Remove Title Bar
root.overrideredirect(True)
# Create Fake Title Bar
title_bar = customtkinter.CTkFrame(master=root, corner_radius=0)
title_bar.pack()
# Titlebar name
title_label = customtkinter.CTkLabel(
master=title_bar, text="custom title bar", width=1633)
title_label.pack(pady=2, padx=0, side='left')
# Close button
close = customtkinter.CTkButton(master=root, text="X", fg_color="#202020",
hover_color="#ff1c1c", width=30, corner_radius=0, command=root.quit)
close.pack(pady=0, padx=0, side='right')
root.mainloop()
Alternatively you could also do it like this:
screen_height = root.winfo_screenheight() - 40
root.geometry(f"{root.winfo_screenwidth()}x{screen_height}+0+0")
This should also work but only on Windows with a 100% aspect ratio and standard taskbar settings. If you use 150% then its 60 and for 200% it's 80.

How to change the window size after the program starts?

I want that after starting the program, it checks its actual size and when "window.winfo_width > 520" it changes its size to 520. Is it possible?
from tkinter import *
from time import *
def upd():
tstr = strftime("%I:%M:%S %p")
ltime.config(text=tstr)
lday.config(text=strftime("%A"))
dtstr = strftime("%B %d, %Y")
ldate.config(text=dtstr)
ltime.after(1000, upd)
window = Tk()
window.config(bg='black')
window.title("Clock")
window.geometry('520x300')
window.resizable(0,1)
ltime = Label(window, font="Adobe 60", text='', fg='green', bg='black')
ltime.pack()
lday = Label(window, font="Adobe 60", text='', fg='green', bg='black')
lday.pack()
ldate = Label(window, font="Adobe 60", text='', fg='green', bg='black')
ldate.pack()
upd()
window.mainloop()
Firstly, window.winfo_geometry() will give you the geometry of the window.
For getting width only, use window.winfo_width().
For getting height only, use window.winfo_height()
e.g.
if window.winfo_width() > 520 :
window.geometry('520x300')
Now, since you are using window.resizable(0,1), you are disabling the window's width to be resized, so windows's width will be fixed to 520.
So, how will it exceed 520, if it's not resizable?
If you enable it, and then want window's width to not exceed 520:
Tkinter offers .maxsize() and .minsize() to fix the size of the root window.
e.g. if you want that the window's width to not exceed 520, then just set the width in maxsize as 520.
window.geometry('520x300')
window.maxsize(520, 300)
The window's width will not be resized more than 520 now.
In case, you want to resize according to the user's screen's size:
To get the screen size, you can use winfo_screenwidth() which returns the screen width and winfo_screenheight() for the height of the screen in pixels.
window.geometry() can be recalled if needed.
EDIT: An example of recalling window.geometry() after the start of program(, even after resizing is disabled horizontally):
def resizeScreen():
window.geometry('520x300')
b = Button(window, text="RESIZE", command=resizeScreen)
b.pack()
Whenever this button is clicked, the screen will be resized, from what it is currently.
You can call this same function without using a button, by just calling the function. It depends on your code, how you use it.

Adding Windows to Buttons on Tkinter GUI

I'm new to Python, I'm trying to add widgets in an window which can be used when we click on an button when in Tkinter GUI.
I'm unable to add an window into the GUI button and I'm doubtful about the Code which can be Implemented as well. I hope I could get some inputs on this.
I'm running on IDLE 3.6.3.I would be grateful if someone could point out the additions that could be made and the changes in the current code.
ConnectLogo=PhotoImage(file="Connect.png")
Connect = Button(win,image=ConnectLogo,text = "Connect", font = myFont,height =100 , width = 100,compound=TOP,bg = "orange")
Connect.grid(row=3,column=1,padx=50,pady=40)
FrequencyLogo=PhotoImage(file="Frequency.png")
Frequency = Button(win,image=FrequencyLogo, text = "Frequency", font = myFont, height = 100, width =180,compound=TOP,bg = "Yellow")
Frequency.grid(row=3,column=2,padx=10)
MaskLogo=PhotoImage(file="Mask.gif")
Mask = Button(win,image=MaskLogo, text = "Mask", font = myFont, height = 100, width =180,compound=TOP,bg = "yellow")
Mask.grid(row=6,column=2,padx=10)
You can make a function, which will implement TopLevel.
This creates a new window into which you can add widgets, add them inside the function.Inside the function you root becomes window
from tkinter import *
root = Tk()
def new_window():
window = TopLevel(root)
...widgets like label, entry etc
label = Label(window,....)
btn = Button(...., command = new_window)
btn.pack()...(anything)

tkinter Canvas method seemilar to Text .see()

I have a Canvas full of buttons, whose ID's I store in a dictionary.
The canvas is very long, with vertical scrollbars.
There is a way to automatically position the view at a given button?
When using a Text, txt.see(position) usually works,
but I see Canvas has no see.
The only possible alternative seems to be .focus(), but cv.focus(ID) doesnt seem to do what I want
There is no ready made function to do that, but you can implement one using yview_moveto(fraction), where fraction is the top fraction of the canvas that will be set off-screen. So, yview_moveto(0) displays the top of the canvas and yview_moveto(1) the bottom.
What we need is to compute the fraction y/h that will display the button identified by iid. h is the height of the content of the canvas and y the height at which the button is in the canvas. I computed them using the canvas bounding box:
def show(iid):
bbox = canvas.bbox('all')
h = bbox[3] - bbox[1]
y = canvas.coords(iid)[1] - bbox[1]
canvas.yview_moveto(y/h)
And below is a small example, type the button ID (between 1 and 20) in the entry and click on 'Show' to shift the view to see it.
import tkinter as tk
def show(iid):
bbox = canvas.bbox('all')
h = bbox[3] - bbox[1]
y = canvas.coords(iid)[1] - bbox[1]
canvas.yview_moveto(y/h)
root = tk.Tk()
canvas = tk.Canvas(root, bg='white')
canvas.pack(fill='both', expand=True)
e = tk.Entry(root)
e.pack()
tk.Button(root, text='Show', command=lambda: show(e.get())).pack()
buttons = {}
for i in range(1, 21):
b = tk.Button(canvas, text='Button %i' % i)
iid = canvas.create_window(0, 30*i, anchor='nw', width=70, height=30, window=b)
buttons[iid] = b
canvas.configure(scrollregion=canvas.bbox('all'))
root.mainloop()

How do you refresh a window in Tkinter

If I created Tkinter window with some text that filled the whole window and now wanted to replace the window with a new text, is there a way to refresh the window?
For Example:
a= 100
win= Tk()
win.geometry("500x300")
while a > 0:
if a%2 == 0:
lbl = Label (win, bg = "purple")
lbl.pack()
else:
lbl = Label (win, bg = "blue")
lbl.pack()
a= x-1
The problem with this code is that the Tkinter window does not refresh and just provides the end result instead of showing the windows changing colors.
Thanks for the help!
That is not the way to change UI states, because even if you refreshed the window it would be so quick you won't notice, instead change the state, wait some time and change the state again e.g. here I show how to animate color
from Tkinter import *
index = 0
def changeColor():
global index
if index%2==0:
label.configure(bg = "purple")
else:
label.configure(bg = "blue")
index+=1
label.after(1000, changeColor)
root = Tk()
mainContainer = Frame(root)
label = Label(mainContainer, text="")
label.configure(text="msg will change every sec")
label.pack(side=LEFT, ipadx=5, ipady=5)
mainContainer.pack()
label.after(1000, changeColor)
root.title("Timed event")
root.mainloop()
This Is How I Do To Update Data From Sql Server in tkinter GUI python3
from tkinter import *
import os
window=Tk()
window.geometry('300x300')
def update():
window.destroy()
os.system('test.py')
Button(window,text="Refresh",command=update)
window.mainloop()

Categories