when i run python file kill_app its run first 2nd python file(Hb_test.py) then run 1st python on tkinter.i am using vs code and python version is 3.10
see the code below
from tkinter import*
from Lab.Hb_Test import Hba
class kill_App:
def __init__(self,root):
self.root = root
self.root.geometry("1350x700+0+0")
self.root.title("Billing Software")
bg_color = "#074463"
title = Label(self.root,text = "PATHOLAB",bd=12,relief=GROOVE,bg=bg_color,fg="white",
font = ("ALGERIAN",40),pady=2).pack(fill=X)
if __name__=="__main__":
root =Tk()
obj = kill_App(root)
root.mainloop()
****
this is my second
**
**from tkinter import*
from tkinter import ttk
class Hba:
def __init__(self,root):
self.root = root
self.root.geometry("300x70+200+200")
self.root.title("JIBAN PRABHA PATHOLAB")
bg_color = "#074463"
Hb = LabelFrame(self.root,text="BLOOD TEST",font=("ALGERIAN",15,"bold")
,fg="gold",bg=bg_color)
Hb.place(x=0,y=0)
self.hb_neu_lbl = Label(Hb,text="Hb%(sahils) Test",bg=bg_color,fg="white",font=("Bell MT",15,"bold")).grid(row=1,column=1,padx=5,pady=5)
self.hb_neu=Entry(Hb,width=10,font="BellMT 15",bd=5,relief=SUNKEN).grid(row=1,column=2,padx=5,pady=5)
root = Tk()
obj = Hba(root)
root.mainloop()**
**
When Hb_Test is imported, its code will be executed, so the last three lines in the module will create a window:
Hb_Test.py
...
# below lines will create a window
root = Tk()
obj = Hba(root)
root.mainloop()
Note that it is not recommended to create more than one instance of Tk() and execute .mainloop() more than once.
For window other than the main/root window, use Toplevel instead of Tk. For your case, I would suggest that Hba inherits from Toplevel:
import tkinter as tk
class Hba(tk.Toplevel):
def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)
self.geometry("300x70+200+200")
self.title("JIBAN PRABHA PATHOLAB")
bg_color = "#074463"
Hb = tk.LabelFrame(self, text="BLOOD TEST", font=("ALGERIAN",15,"bold"), fg="gold", bg=bg_color)
Hb.place(x=0, y=0)
self.hb_neu_lbl = tk.Label(Hb, text="Hb%(sahils) Test", bg=bg_color, fg="white", font=("Bell MT",15,"bold"))
self.hb_neu_lbl.grid(row=1,column=1,padx=5,pady=5)
self.hb_neu = tk.Entry(Hb, width=10, font="BellMT 15", bd=5, relief=tk.SUNKEN)
self.hb_neu.grid(row=1,column=2,padx=5,pady=5)
Note that I have changed from tkinter import * to import tkinter as tk because wildcard import is not recommended as well.
Also don't write code like below:
self.hb_neu_lbl = Label(Hb,text="Hb%(sahils) Test",bg=bg_color,fg="white",font=("Bell MT",15,"bold")).grid(row=1,column=1,padx=5,pady=5)
because self.hb_neu_lbl will be None (result of .grid(...)). Code like below instead:
self.hb_neu_lbl = Label(Hb, text="Hb%(sahils) Test", bg=bg_color, fg="white", font=("Bell MT",15,"bold"))
self.hb_neu_lbl.grid(row=1,column=1,padx=5,pady=5)
Related
i'm a new programmer and there are certainly several errors but this shouldn't be difficult to spot. I need to create a simple window with a field named "Concorrente 1:" and an entry field displayed by function named lacopertina(). I don't understand where is the error:
import tkinter as tk
from tkinter import *
from tkinter.ttk import *
from tkinter import ttk
class schermoiniziale(tk.Frame):
def lacopertina():
print(gio1)
#return (tot1)
def __init__(self):
global gio1
#tot1=0
#schermo1=Tk()
self.gio1=tk.StringVar()
lab1=ttk.Label(self, text="Concorrente 1:")
lab1.pack()
ent1=ttk.Entry(self, textvariable=self.gio1)
ent1.pack()
pulsante = ttk.Button(self, text="Inizio", textvariable=self.gio1, command=self.lacopertina)
pulsante.pack()
def main():
schermoiniziale().mainloop()
if __name__== "__main__":
main()
I would suggest you to go through some tutorials on Python OOP.
I have modified your code as below with some comment:
# avoid using wildcard import
import tkinter as tk
from tkinter import ttk
class schermoiniziale(tk.Frame):
def __init__(self, master, **kw):
# need to call __init__() of inherited class
super().__init__(master, **kw)
self.gio1 = tk.StringVar()
lab1 = ttk.Label(self, text="Concorrente 1:")
lab1.pack()
ent1 = ttk.Entry(self, textvariable=self.gio1)
ent1.pack()
# removed textvariable=self.gio1 as I think you actually don't need it
pulsante = ttk.Button(self, text="Inizio", command=self.lacopertina)
pulsante.pack()
def lacopertina(self):
# use .get() to get the content of a StringVar
print(self.gio1.get())
def main():
# need to create the root window before creating other widget
root = tk.Tk()
# pass root window as the parent of the widget
frame = schermoiniziale(root)
frame.pack()
# start the tkinter mainloop
root.mainloop()
if __name__== "__main__":
main()
Creates two windows and gridding is not correct. Some additional comments in the code initiation.
I have used this approach, without the super init with no problem, many times.
Advice appreciated.
Thanks
# timhockswender#gmail.com
import tkinter as tk
from tkinter import ttk
class constants_page(tk.Frame):
def __init__(self):
super(constants_page, self).__init__() # from stackoverflow
# if not used error = 'constants_page' object has no attribute 'tk'
# if used, another tiny window is opened
# in addtion to the constants_page
self.constants_page = tk.Tk()
self.constants_page.geometry("1000x500") #width*Length
self.constants_page.title("Owen's Unit Conversion App")
self.constants_page.configure(background='light blue')
self.CreateWidgets()
def CreateWidgets(self):
self.value_label = ttk.Label(self.constants_page,text="Value----->" , width =10 )
self.value_label.grid(row=0, column=1, columnspan=1, sticky='nse')
# Problem: not gridding properly
self.title_label = ttk.Label(self.constants_page, text="Important Physical Constants",
anchor=tk.CENTER, font=("Arial",20)).grid(row=2, columnspan=2)
for r in range(2):
self.constants_page.rowconfigure(r, weight=1, uniform='row')
for c in range(2):
self.constants_page.columnconfigure(c, weight=1 )
def Show_Page():
# Create the entire GUI program
program = constants_page()
program.mainloop()
if __name__ == "__main__":
Show_Page()
The super call expects you to provide a root window (an instance of tk.Tk()). If you don't provide one it defaults to the first root window opened, and if none has been opened yet then it helpfully opens one for you. A few lines later you open a second one yourself.
The easy fix is to remove the self.constants_page = tk.Tk() line. The proper fix is to make the Tk() instance outside of the class and pass it in. This allows you to use the Frame class itself to lay out widgets (use self instead of self.constants_page). Try this:
import tkinter as tk
from tkinter import ttk
class constants_page(tk.Frame):
def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)
master.geometry("1000x500") #width*Length
master.title("Owen's Unit Conversion App")
self.configure(background='light blue')
self.CreateWidgets()
def CreateWidgets(self):
self.value_label = ttk.Label(self,text="Value----->" , width =10 )
self.value_label.grid(row=0, column=1, columnspan=1, sticky='nse')
self.title_label = ttk.Label(self, text="Important Physical Constants",
anchor=tk.CENTER, font=("Arial",20)).grid(row=2, columnspan=2)
for r in range(2):
self.rowconfigure(r, weight=1, uniform='row')
for c in range(2):
self.columnconfigure(c, weight=1 )
def Show_Page():
# Create the entire GUI program
program = tk.Tk()
win = constants_page(program)
win.pack()
program.mainloop()
if __name__ == "__main__":
Show_Page()
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()
I want my GUI to have a 'new window' option that will be just the same as the first one.
The problem is that it also has an exit(quit) button that won't work as it should - whenever I open the new window and then press the button, in the first click nothing happens and in the second one it closes both windows (if 3 windows are open so it'll close everything in the third click and so on).
This the relevant code:
from Tkinter import *
from ttk import *
class Application(Tk):
def __init__(self):
self.root = Tk()
self.root.geometry("250x150")
self.app = Frame(self.root)
self.app.grid()
self.create_menu()
self.create_widgets()
self.root.mainloop()
def create_menu(self):
menu = Menu(self.root)
self.root.config(menu=menu)
sub_menu = Menu(menu)
menu.add_cascade(label="File", menu=sub_menu)
sub_menu.add_command(label="New", command=self.__init__)
sub_menu.add_command(label="Run", command=self.enter)
sub_menu.add_separator()
sub_menu.add_command(label="Exit", command=self.app.quit)
I also tried to change:
sub_menu.add_command(label="New", command=self.__init__)
to:
sub_menu.add_command(label="New", command=self.new window)
Where:
def new_window(self):
class App(Application):
Application.__init__(self)
Both do the same thing.
How can I fix it?
In a Tkinter-Application there may only be one Tk-object. If the object is destroyed or destroyed by the garbage collector, Tkinter will be disabled. Use Toplevel for other other windows instead.
Try this instead:
from Tkinter import *
from ttk import *
class Application(object):
def __init__(self, master):
self.root = master
self.root.geometry("250x150")
self.app = Frame(self.root)
self.app.grid()
self.create_menu()
self.create_widgets()
def create_menu(self):
menu = Menu(self.root)
self.root.config(menu=menu)
sub_menu = Menu(menu)
menu.add_cascade(label="File", menu=sub_menu)
sub_menu.add_command(label="New", command=self.new)
sub_menu.add_command(label="Run", command=self.enter)
sub_menu.add_separator()
sub_menu.add_command(label="Exit", command=self.quit)
def new(self):
window = Toplevel(tk)
return Application(window)
def quit(self):
tk.destroy()
tk = Tk()
Application(tk)
tk.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()