How to bind resize event? my event broken.
I found weird 2 conditions if i sets condition greater width 600 font-size 5. it will trigger event once only.
the other condition if i sets font-size to 12. no event trigger.
style.py
import tkinter.ttk as ttk
class Style(ttk.Style):
_window = None
def __init__(self, window):
super().__init__(window)
self._window = window
self.configure("USERINFO.TLabel", font=('script', 12))
self._window.bind("<Configure>", self.__resize)
def __resize(self, event):
if event.width > 600:
self.configure("USERINFO.TLabel", font=('Helvetica', 5))
else:
self.configure("USERINFO.TLabel", font=('script', 12))
guy.py
import tkinter
import tkinter.ttk as ttk
from style import Style
class MainWindow(tkinter.Tk):
def __init__(self):
super().__init__()
Style(self)
self._clientarea()
def _clientarea(self):
frame = ttk.Frame(self).grid(column=0, row=0)
ttk.Label(frame, text="Username: ", style="USERINFO.TLabel").grid(column=0, row=0)
if __name__ == "__main__":
root = MainWindow()
root.mainloop()
Related
I'm trying to create a sample GUI using tkinter with customtkinter module ,but nothing appears in the window.
import tkinter
import tkinter.messagebox
import customtkinter
customtkinter.set_appearance_mode("System")
customtkinter.set_default_color_theme("green")
class App(customtkinter.CTk):
def __init__(self):
super().__init__()
# configure window
self.title("Tracking System")
self.geometry("350x500")
self.resizable(False,False) # to disable the minimize/maximize buttons.
self.checkbox_slider_frame = customtkinter.CTkFrame(self)
self.switch = customtkinter.CTkSwitch(master=self.checkbox_slider_frame, command=lambda: print("switch 1 toggle"))
self.switch.grid(row=0, column=0)
self.switch.select()
self.button = customtkinter.CTkButton(master=self.checkbox_slider_frame, text="CTkButton")
self.button.grid(row=1 , column = 1)
if __name__ == "__main__":
app = App()
app.mainloop()
I looked into the customtkinter example:-
https://github.com/TomSchimansky/CustomTkinter/blob/master/examples/complex_example.py
But I
You forgot to add self.checkbox_slider_frame to a geometry manager (pack, place, or grid)
self.checkbox_slider_frame = customtkinter.CTkFrame(self)
self.checkbox_slider_frame.pack(expand=True, fill=tkinter.BOTH)
I have created a notebook and added a frame to it:
nb = ttk.Notebook(root, style="TNotebook")
page1 = ttk.Frame(nb, style='Frame1.TFrame')
layout1(page1)
nb.add(page1, text='Welcome')
So i have a function layout1, the first page of the notebook,
i added to it a Text:
def layout1(page):
entry = Text(page, width=20)
entry.place(relx=0.03, rely=0.1, height=400)
Button(page, text='EXECUTE', command=import_entry).place(relx=0.5, rely=0.6)
And next i have my import_entry function:
def import_entry():
result = entry.get()
print(result)
I can't get the entry because of accessibilty of variables in function. So, how can i get it?
Here is an example of how you should structure your app with a class:
import tkinter
import tkinter.ttk as ttk
class App(tkinter.Tk):
def __init__(self):
super().__init__()
# assign on_closing method to window close event
self.protocol("WM_DELETE_WINDOW", self.on_closing)
self.title("Example App")
self.geometry("600x500")
self.button_1 = tkinter.Button(master=self, text="Test", command=self.button_event)
self.button_1.pack(pady=10)
# create more widgets ...
def button_event(self, event):
print("button pressed")
def on_closing(self):
# code that needs to happen when gets closed
self.destroy() # controlled closing of window with .destroy()
if __name__ == "__main__":
app = App()
app.mainloop()
I have made a simple GUI that has two buttons for a Square function and Exit button. I want to print the results on the canvas as shown in the expected results.
Here are my codes
from tkinter import *
from PIL import Image,ImageTk
from tkinter import filedialog
from PIL import Image, ImageTk
import os
import cv2
import numpy as np
import time
class application(Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.minsize(width=300,height=500)
self.initialize()
def initialize(self):
self.grid_columnconfigure(0,weight=1)
self.grid_columnconfigure(1,weight=1)
self.grid_columnconfigure(2,weight=1)
#Button widgets
###########################################################################################
self.button1 = Button(self,text='Square',bg= 'blue',width=15,height=2, command =Square)
self.button1.grid(column=0,row=1,sticky='W',pady=5)
self.button3 = Button(self,text='Exit',bg= 'blue',width=10,height=2,command=self.destroy)
self.button3.grid(column=1,row=5,sticky='W',pady=5)
#Text widget for inserting the result
############################################################################################
self.canvas = Canvas(self,width=230,height=180,state=NORMAL)
self.canvas.grid(column=0,row=4,sticky='W',padx=100,pady=10)
#self.canvas.configure(bg='green')
#Label widget
############################################################################################
self.label3 = Label(self,text="Square",bg = 'red',width=10,height=2,anchor="center")
self.label3.grid(column=0,row=3,sticky='W',padx=120)
def Square(self):
for i in range(1,10):
y = i**2
print(i, y)
if __name__ == "__main__":
app = application(None)
#font.nametofont('TkDefaultFont').configure(size=10)
app['bg']='red'
app.title("square")
app.mainloop()
My expected results are given in the image below
Not entirely sure what you are asking. But, if you just want to create text on canvas use canvas.create_text(x, y, text).
from tkinter import *
from PIL import Image,ImageTk
class application(Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.minsize(width=300,height=500)
self.initialize()
def initialize(self):
self.grid_columnconfigure(0,weight=1)
self.grid_columnconfigure(1,weight=1)
self.grid_columnconfigure(2,weight=1)
#Button widgets
###########################################################################################
self.button1 = Button(self,text='Square',bg= 'blue',width=15,height=2, command=self.Square)
self.button1.grid(column=0,row=1,sticky='W',pady=5)
self.button3 = Button(self,text='Exit',bg= 'blue',width=10,height=2,command=self.destroy)
self.button3.grid(column=1,row=5,sticky='W',pady=5)
#Text widget for inserting the result
############################################################################################
self.canvas = Canvas(self,width=230,height=180,state=NORMAL)
self.canvas.grid(column=0,row=4,sticky='W',padx=100,pady=10)
#self.canvas.configure(bg='green')
self.label3 = Label(self,text="Square",bg = 'red',width=10,height=2,anchor="center")
self.label3.grid(column=0,row=3,sticky='W',padx=120)
def Square(self):
for i in range(1,10):
y = i**2
print(i, y)
c_id = self.canvas.create_text(0, 20, text=f"{i}\t{y}", fill="blue", font="Times 14")
bbox = self.canvas.bbox(c_id)
self.canvas.coords(c_id, 100, bbox[3]*i)
if __name__ == "__main__":
app = application(None)
#font.nametofont('TkDefaultFont').configure(size=10)
app['bg']='red'
app.title("square")
app.mainloop()
I currently working on some code on Tkinter and I want to know if its possibly and if so how to add a website hyperlink to a button. In my case I'm trying to add the Caldicot School web address to a button through Tkinter on Python 3 and when its clicked it sends you there
Welcome to SO!
This page has a recipe for creating a button that acts like a hyperlink in tkinter
http://code.activestate.com/recipes/580774-tkinter-link-or-hyperlink-button/
The main part of the code is as follows:
if __name__ == "__main__":
import webbrowser
try:
from Tkinter import Tk, Frame
except ImportError:
from tkinter import Tk, Frame
def callback():
webbrowser.open_new(r"http://www.google.com")
root = Tk()
frame = Frame(root, bg="white")
frame.pack(expand=True, fill="both")
# Creates a button that, when clicked, calls the function that sends you to your hyperlink.
link = Link_Button(frame, text="Google Hyperlink", action=callback)
link.pack(padx=10, pady=10)
root.mainloop()
Check the website above for the code behind the class Link_Button. In case the link dies, here's the rest of the code:
# Author: Miguel Martinez Lopez
try:
from Tkinter import Label
from ttk import Style
from tkFont import Font, nametofont
except ImportError:
from tkinter import Label
from tkinter.ttk import Style
from tkinter.font import Font, nametofont
def get_background_of_widget(widget):
try:
# We assume first tk widget
background = widget.cget("background")
except:
# Otherwise this is a ttk widget
style = widget.cget("style")
if style == "":
# if there is not style configuration option, default style is the same than widget class
style = widget.winfo_class()
background = Style().lookup(style, 'background')
return background
class Link_Button(Label, object):
def __init__(self, master, text, background=None, font=None, familiy=None, size=None, underline=True, visited_fg = "#551A8B", normal_fg = "#0000EE", visited=False, action=None):
self._visited_fg = visited_fg
self._normal_fg = normal_fg
if visited:
fg = self._visited_fg
else:
fg = self._normal_fg
if font is None:
default_font = nametofont("TkDefaultFont")
family = default_font.cget("family")
if size is None:
size = default_font.cget("size")
font = Font(family=family, size=size, underline=underline)
Label.__init__(self, master, text=text, fg=fg, cursor="hand2", font=font)
if background is None:
background = get_background_of_widget(master)
self.configure(background=background)
self._visited = visited
self._action = action
self.bind("<Button-1>", self._on_click)
#property
def visited(self):
return self._visited
#visited.setter
def visited(self, is_visited):
if is_visited:
self.configure(fg=self._visited_fg)
self._visited = True
else:
self.configure(fg=self._normal_fg)
self._visited = False
def _on_click(self, event):
if not self._visited:
self.configure(fg=self._visited_fg)
self._visited = True
if self._action:
self._action()
You can basicly add this method:
from tkinter import *
from tkinter import ttk
import webbrowser
root = Tk()
root.title = 'Link Button'
def link():
webbrowser.open_new(r"https://www.python.org")
and then link method to the button:
nut = ttk.Button(root, text='Link Button', command=link)
nut.pack()
root.mainloop()
import tkinter
import webbrowser
root = Tk()
root.title = 'link to the button'
def link():
webbrowser.open_new(r"https://www.python.org")
nut = ttk.Button(root, text='link to the button')
nut.pack()
root.mainloop()
and then just simply use
nut = ttk.Button(root, text= 'link to the button', command=link)
nut.pack()
root.mainloop()
so when i run this code and click the button:
from Tkinter import *
import thread
class App:
def __init__(self, master):
print master
def creatnew():
admin=Tk()
lab=Label(admin,text='Workes')
lab.pack()
admin.minsize(width=250, height=250)
admin.maxsize(width=250, height=250)
admin.configure(bg='light green')
admin.mainloop()
def other():
la=Label(master,text='other')
la.pack()
bu=Button(master,text='clicks',command=lambda: thread.start_new_thread(creatnew,()))
bu.pack()
other()
Admin = Tk()
Admin.minsize(width=650, height=500)
Admin.maxsize(width=650, height=500)
app = App(Admin)
Admin.mainloop()
i get a second tkinter window but its a white blank screen that makes both programs not respond.
any ideas
Don't use threads. It's confusing the Tkinter mainloop. For a second window create a Toplevel window.
Your code with minimal modifications:
from Tkinter import *
# import thread # not needed
class App:
def __init__(self, master):
print master
def creatnew(): # recommend making this an instance method
admin=Toplevel() # changed Tk to Toplevel
lab=Label(admin,text='Workes')
lab.pack()
admin.minsize(width=250, height=250)
admin.maxsize(width=250, height=250)
admin.configure(bg='light green')
# admin.mainloop() # only call mainloop once for the entire app!
def other(): # you don't need define this as a function
la=Label(master,text='other')
la.pack()
bu=Button(master,text='clicks',command=creatnew) # removed lambda+thread
bu.pack()
other() # won't need this if code is not placed in function
Admin = Tk()
Admin.minsize(width=650, height=500)
Admin.maxsize(width=650, height=500)
app = App(Admin)
Admin.mainloop()