tkinter frames not showing the widgets - python

from tkinter import *
import tkinter.messagebox
def message():
text='''sfjkasjdfkjasdfjsdjfjsdlfjasd
fjsdkfjksadjfsajdjfl
sdfasdjflsjdlfsldjflsjd'''
tkinter.messagebox.showinfo("showing",text)
def _price_inputs():
win2 = Tk()
win2.title("Transactions for the project Botique")
win2.geometry("1600x800+0+0")
win2.configure(bg="black")
framex = Frame(win2,width=1600,bg="RoyalBlue4",height=100,relief=GROOVE).pack(side=TOP)
frame1 = Frame(win2,width=1000, height=400,bg="white", relief=SUNKEN).pack(side=RIGHT,fill=Y)
frame2 = Frame(win2, width=775,height=100,bg="white", relief=FLAT).pack(side=BOTTOM)
frame3 = Frame(win2,width=600,height=430,bg="gray",relief=FLAT).pack(side=LEFT,fill=X)
#framex == heading
#frame1 == showing the infos
#frame2 == bottom_infos
#frme3 == adding the buttons and widgets
#==++++===========================title=============================
lbl1 = Label(framex,font=("arial", 30, "bold"),bg="powder blue",fg="green",text="Hello this is the title of the page",bd=10,relief=GROOVE).pack(side=TOP)
btn1 = Button(frame1,font=("arial",20,"bold"),bg="powder blue",fg="white",text="click me").pack()
win2.mainloop()
I am trying to create the gui with tkinter.I am using python3.6
I made frames using tkinter and now when i try to add buttons , Labels etc it doesen't show the buttons or Labels in the output screen.
And how to i use pack for frames and grid for widgets in that frame using the pack.

You haven't call function in which you have defined properties. Just call function by adding _price_inputs() to your code at last:
from tkinter import *
import tkinter.messagebox
def message():
text='''sfjkasjdfkjasdfjsdjfjsdlfjasd
fjsdkfjksadjfsajdjfl
sdfasdjflsjdlfsldjflsjd'''
tkinter.messagebox.showinfo("showing",text)
def _price_inputs():
win2 = Tk()
win2.title("Transactions for the project Botique")
win2.geometry("1600x800+0+0")
win2.configure(bg="black")
framex = Frame(win2,width=1600,bg="RoyalBlue4",height=100,relief=GROOVE).pack(side=TOP)
frame1 = Frame(win2,width=1000, height=400,bg="white", relief=SUNKEN).pack(side=RIGHT,fill=Y)
frame2 = Frame(win2, width=775,height=100,bg="white", relief=FLAT).pack(side=BOTTOM)
frame3 = Frame(win2,width=600,height=430,bg="gray",relief=FLAT).pack(side=LEFT,fill=X)
#framex == heading
#frame1 == showing the infos
#frame2 == bottom_infos
#frme3 == adding the buttons and widgets
#==++++===========================title=============================
lbl1 = Label(framex,font=("arial", 30, "bold"),bg="powder blue",fg="green",text="Hello this is the title of the page",bd=10,relief=GROOVE).pack(side=TOP)
btn1 = Button(frame1,font=("arial",20,"bold"),bg="powder blue",fg="white",text="click me").pack()
win2.mainloop()
_price_inputs()

You can't see new items, lbl1 and btn1 as they're:
Children to win2, not any frames
Blocked by another frame, frame3
1
lbl1 and btn1 are children to win2, because passing None as the first positional argument or by default, the widget's parent is assigned as the Tk instance.
lbl1 and btn1 are instantiated with parent arguments as None, because:
framex = Frame(win2,width=1600,bg="RoyalBlue4",height=100,relief=GROOVE).pack(side=TOP)
...
frame1 = Frame(win2,width=600,height=430,bg="red",relief=FLAT).pack(side=LEFT,fill=X)
lines are identical to that of:
Frame(win2,width=1600,bg="RoyalBlue4",height=100,relief=GROOVE).pack(side=TOP)
framex = None
...
Frame(win2,width=600,height=430,bg="red",relief=FLAT).pack(side=LEFT,fill=X)
frame1 = None
Because both framex and frame3 are the return of the method pack which is always None.
One could fix this by separating the geometry manager line with the widget instantiation line:
framex = Frame(win2,width=1600,bg="RoyalBlue4",height=100,relief=GROOVE)
framex.pack(side=TOP)
...
frame1 = Frame(win2,width=600,height=430,bg="red",relief=FLAT)
frame1.pack(side=LEFT,fill=X)
2
Comment out frame3 line to see that lbl1 and btn1 actually exists:
#frame3 = Frame(win2,width=600,height=430,bg="red",relief=FLAT).pack(side=LEFT,fill=X)

from tkinter import *
import tkinter.messagebox
"""def message():
text='''sfjkasjdfkjasdfjsdjfjsdlfjasd
fjsdkfjksadjfsajdjfl
sdfasdjflsjdlfsldjflsjd'''
tkinter.messagebox.showinfo("showing",text)"""
def _price_inputs():
win2 = Tk()
win2.title("Transactions for the project Botique")
win2.geometry("1600x800+0+0")
win2.configure(bg="white")
framex = Frame(win2,width=1600,bg="RoyalBlue4",height=100,relief=GROOVE).pack(side=TOP)
#frame1 = Frame(win2,width=1000, height=400,bg="white", relief=SUNKEN).pack(side=RIGHT,fill=Y)
frame2 = Frame(win2, width=775,height=100,bg="black", relief=FLAT).pack(side=BOTTOM)
frame3 = Frame(win2,width=800,height=450,bg="gray",relief=FLAT).pack(side=LEFT,fill=X)
#framex == heading
#frame1 == showing the infos
#frame2 == bottom_infos
#frme3 == adding the buttons and widgets
#==++++===========================title=============================
lbl1 = Label(framex,font=("arial", 30, "bold"),bg="black",fg="green",text="Hello this is the title of the page",bd=10,relief=GROOVE).pack(side=TOP)
btn1 = Button(frame3,font=("arial",15,"bold"),bd=8,bg="black",fg="white",text="before 60 hrs",relief=GROOVE).pack(side=BOTTOM)
btn2 = Button(frame3,font=("arial",15,"bold"),bd=8,bg="black",fg="white",text="full_stock",relief=GROOVE).pack(side=BOTTOM)
btn3 = Button(frame3,font=("arial",15,"bold"),bd=8,bg="black",fg="white",text="delivery_report",relief=GROOVE).pack(side=BOTTOM)
before = IntVar()
stock_full = IntVar()
delivery_report = IntVar()
btn4 = Button(win2,font=("arial",15,"bold"),bd=8,bg="black",fg="white",text="hello",relief=GROOVE).pack(side=BOTTOM)
'''import Tkinter as tk
import ImageTk
FILENAME = 'image.png'
root = tk.Tk()
canvas = tk.Canvas(root, width=250, height=250)
canvas.pack()
tk_img = ImageTk.PhotoImage(file = FILENAME)
canvas.create_image(125, 125, image=tk_img)
quit_button = tk.Button(root, text = "Quit", command = root.quit, anchor = 'w',
width = 10, activebackground = "#33B5E5")
quit_button_window = canvas.create_window(10, 10, anchor='nw', window=quit_button)
root.mainloop()
'''
win2.mainloop()

Related

create a scrollbar on entry with cavnas, python tkinter

I'm trying to put a scrollbar on entry that created on canvas..
I've tried this code
from tkinter import *
root = Tk()
root.geometry('400x600')
root.resizable(0,0)
page = Canvas(root, width=400, height=600, bd=0, highlightthickness=0,scrollregion=(0,0,500,500))
MyImage1 = PhotoImage(file='Study With4.png')
CanvasImage = page.create_image(0,0,image= MyImage1, anchor='nw')
entry =Text(page,height=29,width =46,wrap=WORD,bg='#F8F8F8')
scroll = Scrollbar(entry, orient=VERTICAL)
scroll.pack(side=RIGHT, fill=Y)
scroll.config(command=page.yview)
page.config(yscrollcommand=scroll.set)
page.create_window(200,285, window=entry)
page.pack()
mainloop()
but it doesn't work and I don't know where is the problem.
I've made minimal changes to your code, the biggest is creating a Frame called "label"
to contain Text and Scrollbar then inserting that into Canvas window.
Your scroll object was not defined properly with confusion around page and entry objects.
from tkinter import *
root = Tk()
root.geometry('500x600')
root.resizable(0,0)
page = Canvas(
root, width = 500, height = 600, bd = 0,
highlightthickness = 0,scrollregion = (0,0,1000,1000))
page.pack(side = LEFT, fill = BOTH, expand = True)
MyImage1 = PhotoImage(file='Study With4.png')
CanvasImage = page.create_image(0, 0, image = MyImage1, anchor = NW)
label = Frame(root)
label.pack(fill = BOTH, expand = True)
entry = Text(label, height = 29, width = 46, wrap = NONE, bg = '#F8F8F8')
entry.pack(side = LEFT, fill = BOTH, expand = True)
scroll = Scrollbar(label, orient = VERTICAL)
scroll.pack(side=RIGHT, fill=Y)
scroll.config(command = entry.yview)
entry.config(yscrollcommand = scroll.set)
page.pack()
page.create_window(25, 25, window = label, anchor = NW)
mainloop()

How do I make python tkinter widgets appear on the right side of a frame and grow left?

Current behavior, adding LabelFrame widgets (with their own label and picture children) into another Labelframe named "Test putting buffs..." The LabelFrame widgets are being added into the left side of the LabelFrame and "grow" to the right. Wanted behavior is for the widgets to appear on the right side of the frame and "grow" left.
Cannot seem to get there with anchor or sticky settings. How can this "grow-left" be done and still preserve the ability to sort by name or time remaining?
Current behavior gif:
Wanted behavior (mocked up with paint):
Code (took out the image stuff so files aren't needed to run):
import tkinter as tk
from tkinter import ttk
from PIL import ImageTk, Image
import time
class MainFrame(tk.Frame):
def __init__(self, container):
super().__init__(container)
self.grid(column=0, row=0)
self.buffs_list_frames = []
self.button1 = ttk.Button(self)
self.button1['text'] = "Simulate frame list appended True Strike"
self.button1['command'] = lambda: self.buffs_frame_list_is_appended(["True Strike", time.time() + 9])
self.button1.grid(column=0, row=0)
self.button2 = ttk.Button(self)
self.button2['text'] = "Simulate frame list appended Bulls"
self.button2['command'] = lambda: self.buffs_frame_list_is_appended(["Bulls", time.time() + 1080])
self.button2.grid(column=0, row=1)
self.button0 = ttk.Button(self)
self.button0['text'] = "Simulate frame list appended Endurance"
self.button0['command'] = lambda: self.buffs_frame_list_is_appended(["Endurance", time.time() + 1080])
self.button0.grid(column=0, row=2)
self.button3 = ttk.Button(self)
self.button3['text'] = "Simulate frame list put into .grid() and displayed"
self.button3['command'] = lambda: self.buffs_display_nicely()
self.button3.grid(column=0, row=3)
self.button4 = ttk.Button(self)
self.button4['text'] = "START loops of time passing"
self.button4['command'] = lambda: self.buffs_loop_time_passing()
self.button4.grid(column=0, row=4)
self.test_label_frame = ttk.LabelFrame(self, text="Testing putting buffs into a frame with grid")
self.test_label_frame.grid(column=1, row=0)
def buffs_loop_time_passing(self):
for x in self.buffs_list_frames:
x.buff_timer.set(f"{x.buff_birthday - time.time():.1f}s")
if x.buff_birthday < time.time() + 6:
x['background'] = 'red'
if x.buff_birthday < time.time():
self.buffs_list_frames.remove(x)
x.destroy()
self.after(1000, self.buffs_loop_time_passing)
def buffs_frame_list_is_appended(self, added_buff):
""" makes the buff frame and adds to the list of frame widgets
"""
self.buff_frame = tk.LabelFrame(self.test_label_frame, borderwidth=1, text=added_buff[0][0:4], labelanchor="n")
# self.buff_frame.buff_image_reference = ImageTk.PhotoImage(Image.open(added_buff[2]))
# self.buff_frame.buff_image_label = ttk.Label(self.buff_frame, image=self.buff_frame.buff_image_reference)
# self.buff_frame.buff_image_label.image_keep = self.buff_frame.buff_image_reference
# self.buff_frame.buff_image_label.grid(column=0, row=0)
self.buff_frame.buff_birthday = added_buff[1]
self.buff_frame.buff_timer = tk.StringVar()
self.buff_frame.buff_timer.set(f"{self.buff_frame.buff_birthday - time.time():.1f}s")
self.buff_frame.buff_label = ttk.Label(self.buff_frame, textvariable=self.buff_frame.buff_timer)
self.buff_frame.buff_label.grid(column=0, row=1)
self.buffs_list_frames.append(self.buff_frame)
self.buffs_display_nicely()
def buffs_display_nicely(self):
""" takes the list of frames, sorts by name, and .grids()s them into the test frame
"""
self.buffs_list_frames = sorted(self.buffs_list_frames, key=lambda z: z['text'])
print(f"sorted? {self.buffs_list_frames}")
j = 0
for x in self.buffs_list_frames:
x.grid(row=0, column=j)
j += 1
class App(tk.Tk):
def __init__(self):
super().__init__()
# configure the root window
self.title('NWN Buff Watcher')
self.geometry('300x50')
if __name__ == "__main__":
app = App()
main_frame = MainFrame(app)
app.mainloop()
Try this (using #acw1668's suggestion):
import tkinter as tk
from tkinter import ttk
from PIL import ImageTk, Image
import time
class MainFrame(tk.Frame):
def __init__(self, container):
super().__init__(container)
self.buffs_list_frames = []
self.buttons_frame = tk.Frame(self)
self.buttons_frame.pack(fill="both", side="left")
self.button1 = ttk.Button(self.buttons_frame, text="Simulate frame list appended True Strike",
command=lambda: self.buffs_frame_list_is_appended("True Strike", 9))
self.button1.grid(column=0, row=0)
self.button2 = ttk.Button(self.buttons_frame, text="Simulate frame list appended Bulls",
command=lambda: self.buffs_frame_list_is_appended("Bulls", 1080))
self.button2.grid(column=0, row=1)
self.button0 = ttk.Button(self.buttons_frame, text="Simulate frame list appended Endurance",
command=lambda: self.buffs_frame_list_is_appended("Endurance", 1080))
self.button0.grid(column=0, row=2)
#self.button3 = ttk.Button(self.buttons_frame, text="Order items", command=self.order_items)
#self.button3.grid(column=0, row=3)
self.button4 = ttk.Button(self.buttons_frame, text="START loops of time passing",
command=self.buffs_loop_time_passing)
self.button4.grid(column=0, row=4)
self.test_label_frame = ttk.LabelFrame(self, text="Testing putting buffs into a frame with grid")
self.test_label_frame.pack(side="right")
def buffs_loop_time_passing(self):
for x in self.buffs_list_frames:
x.buff_timer.set(f"{x.buff_birthday - time.time():.1f}s")
time_now = time.time()
if x.buff_birthday < time_now + 6:
x.config(bg="red")
if x.buff_birthday < time_now:
self.buffs_list_frames.remove(x)
x.destroy()
self.after(100, self.buffs_loop_time_passing)
def buffs_frame_list_is_appended(self, added_buff, time_alive):
""" makes the buff frame and adds to the list of frame widgets
"""
buff_frame = tk.LabelFrame(self.test_label_frame, borderwidth=1,
text=added_buff[:4], labelanchor="n")
# buff_frame.buff_image_reference = ImageTk.PhotoImage(Image.open(added_buff[2]), master=self)
# buff_frame.buff_image_label = ttk.Label(buff_frame, image=buff_frame.buff_image_reference)
# buff_frame.buff_image_label.image_keep = buff_frame.buff_image_reference
# buff_frame.buff_image_label.grid(column=0, row=0)
buff_frame.buff_birthday = time.time() + time_alive
buff_frame.buff_timer = tk.StringVar(master=self)
buff_frame.buff_timer.set(f"{buff_frame.buff_birthday - time.time():.1f}s")
buff_frame.buff_label = ttk.Label(buff_frame,
textvariable=buff_frame.buff_timer)
buff_frame.buff_label.grid(column=0, row=1)
self.buffs_list_frames.append(buff_frame)
self.order_items()
def order_items(self):
self.buffs_list_frames = sorted(self.buffs_list_frames, key=lambda z: z['text'], reverse=True)
for x in self.buffs_list_frames:
x.pack_forget()
x.pack(side="right")
class App(tk.Tk):
def __init__(self):
super().__init__()
# configure the root window
self.title("NWN Buff Watcher")
# self.geometry("300x50")
if __name__ == "__main__":
app = App()
main_frame = MainFrame(app)
main_frame.pack()
app.mainloop()
I made a few changes to your code. The main thing is that I removed buffs_display_nicely and instead added buff_frame.pack(side="right"). The side="right" tells tkinter to add the widgets from the right to the left.
Also you can improve your code by a lot if you add a class instead of using buff_frame.buff_birthday, buff_frame.buff_timer, ... Also it will make your life a lot easier

problem with tkinter under defined function

Can you please help me with follwing issue I face:
When I am creating radiobutton with tkinter, I don't have a problem to select from the list.
However, if I put the same script under a menu, then selected option is always the default one, ("Python",1) in this specific case. Do you have any idea how to overcome this? Thanks in advance!
import tkinter as tk
root_m = tk.Tk()
root_m.geometry("400x200")
frame_m = tk.Frame(root_m)
root_m.title("NUMERIC UNIVERSE")
frame_m.pack()
def chars_merging():
languages = [
("Python",1),
("Perl",2),
("Java",3),
("C++",4),
("C",5)
]
root = tk.Tk()
root.geometry("400x200")
frame = tk.Frame(root)
root.title("SELECT SOMETHING")
frame.pack()
v = tk.IntVar()
v.set(0) # initializing the choice, i.e. Python
label = tk.Label(frame,
text="""Choose your favourite
programming language:""",
justify = tk.LEFT,
padx = 20)
label.pack()
def ShowChoice():
global data_sel
data_sel = v.get()
print(data_sel)
for val, language in enumerate(languages):
tk.Radiobutton(frame,
text=language,
indicatoron = 0,
width = 20,
padx = 20,
variable=data_sel,
command=ShowChoice,
value=val).pack(anchor=tk.W)
root.mainloop()
#return(languages[v.get()])
print("You selected", languages[v.get()])
button3 = tk.Button(frame_m,
text="3.Prepare and merge chars",
command=chars_merging,
width=25)
button3.pack()
# CLOSING THE WINDOW ---------------------------------------------------------
def finish():
root_m.destroy()
button_n = tk.Button(frame_m,
text="Finish",
command=finish,
width=25)
button_n.pack()
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
root_m.mainloop()

How to replace an existing image instead of adding additional images?

This is my first time here, and I would really appreciate some help with this.
So I have some code which runs a Tkinter tab and shows 2 buttons. If you click the first one, a picture of a cat appears.
However, if you click the button again, the same picture appears again at the bottom, making there 2.
If I click the other button, titled N/A, a different picture appears. But if you click the button again, the picture duplicates.
I want to make it so that when each button is pressed, the image is replaced, not duplicated.
Here is what I have so far.
from tkinter import *
root = Tk()
class HomeClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text="Welcome to the game!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.FirstButton = Button(root, text="Start", bg="RED", fg="White",
command=self.FirstClick)
self.FirstButton.pack(side=LEFT, fill=X)
self.SecondButton = Button(root, text="N/A", bg="Blue", fg="White",
command=self.SecondClick)
self.SecondButton.pack(side=LEFT, fill=X)
def FirstClick(self):
FirstPhoto = PhotoImage(file="keyboardcat.gif")
FiLabel = Label(root, image=FirstPhoto)
FiLabel.img = FirstPhoto
FiLabel.pack()
def SecondClick(self):
FirstPhoto = PhotoImage(file="donald.gif")
FiLabel = Label(root, image=FirstPhoto)
FiLabel.img = FirstPhoto
FiLabel.pack()
k = HomeClass(root)
root.mainloop()
That's becouse every time you click a button, you're calling FirstClick method which in turn creates new instance of PhotoImage class. I think it would be better to store FirstPhoto and in every FirstClick method call check if it is already has value or not.
class HomeClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text="Welcome to the game!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.FirstButton = Button(root, text="Start", bg="RED", fg="White",
command=self.FirstClick)
self.FirstButton.pack(side=LEFT, fill=X)
self.SecondButton = Button(root, text="N/A", bg="Blue", fg="White",
command=self.SecondClick)
self.SecondButton.pack(side=LEFT, fill=X)
self.FirstPhoto = None
def FirstClick(self):
if self.FirstPhoto is None:
self.FirstPhoto = PhotoImage(file="ksiazka.png")
self.FiLabel = Label(root, image=self.FirstPhoto)
self.FiLabel.img = self.FirstPhoto
self.FiLabel.pack()
Try this to change SecondPhoto
def SecondClick(self):
if self.SecondPhoto is None:
self.SecondPhoto = PhotoImage(file="ksiazka.png")
self.SecondPhotoLabel = Label(root, image=self.FirstPhoto)
self.SecondPhotoLabel.img = self.SecondPhoto
self.SecondPhotoLabel.pack()
Else:
self.SecondPhotoLabel.config(image='newimage')
self.SecondPhotoLabel.update()
Note - you can declare the newImage before as you have to read it with PhotoImage and then just put the image name in the .config
In this example you have two methods FirstClick, SecondClick to display an image and two methods to clear an first and second image accordingly: clearFirstImage, clearSecondImage. You just have to add two buttons to trigger those clear methods :)
from tkinter import *
from tkFileDialog import askopenfilename
root = Tk()
class HomeClass(object):
def __init__(self, master):
self.master = master
self.frame = Frame(master)
self.WelcomeLabel = Label(root, text="Welcome to the game!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.FirstButton = Button(root, text="Start", bg="RED", fg="White",
command=self.FirstClick)
self.FirstButton.pack(side=LEFT, fill=X)
self.SecondButton = Button(root, text="N/A", bg="Blue", fg="White",
command=self.SecondClick)
self.SecondButton.pack(side=LEFT, fill=X)
self.ToggleButtonText = "Show image"
self.ToggleButton = Button(root, text=self.ToggleButtonText, bg="Grey", fg="White",
command=self.ToggleClick)
self.ToggleButton.pack(side=LEFT, fill=X)
self.FirstPhoto = None
self.FiLabel = None
self.SecondPhoto = None
self.SecondPhotoLabel = None
self.ToggleButtonPhoto = None
self.ToggleButtonPhotoLabel = None
self.frame.pack()
def FirstClick(self):
if self.FirstPhoto is None:
self.FirstPhoto = PhotoImage(file="ksiazka.png")
self.FiLabel = Label(root, image=self.FirstPhoto)
self.FiLabel.img = self.FirstPhoto
self.FiLabel.pack()
def ToggleClick(self):
if self.ToggleButtonPhoto is None:
self.ToggleButtonPhoto = PhotoImage(file="ksiazka.png")
self.ToggleButtonPhotoLabel = Label(self.frame, image=self.ToggleButtonPhoto)
self.ToggleButtonPhotoLabel.img = self.ToggleButtonPhoto
self.ToggleButtonPhotoLabel.pack()
# and set label
self.ToggleButton.config(text="Hide image")
else:
self.ToggleButton.config(text="Show image")
self.ToggleButtonPhotoLabel.destroy()
self.ToggleButtonPhotoLabel.img = None
self.ToggleButtonPhotoLabel = None
self.ToggleButtonPhoto = None
self.frame.pack()
def SecondClick(self):
filename = askopenfilename()
allowed_extensions = ['jpg', 'png']
if len(filename) > 0 and filename.split('.')[-1] in allowed_extensions:
self.SecondPhoto = PhotoImage(file=filename)
self.SecondPhotoLabel = Label(root, image=self.SecondPhoto)
self.SecondPhotoLabel.img = self.SecondPhoto
self.SecondPhotoLabel.pack()
def clearFirstImage(self):
self.FirstPhoto = None
self.FiLabel = None
def clearSecondImage(self):
self.SecondPhoto = None
self.SecondPhotoLabel = None
k = HomeClass(root)
root.mainloop()
If you want to replace an existing image, first create the label the image is displayed in, and simply reconfigure only its image option with each click. Below is an example that does that:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def download_images():
# In order to fetch the image online
try:
import urllib.request as url
except ImportError:
import urllib as url
url.urlretrieve("https://i.stack.imgur.com/57uJJ.gif", "13.gif")
url.urlretrieve("https://i.stack.imgur.com/8LThi.gif", "8.gif")
class ImageFrame(tk.Frame):
def __init__(self, master, *args, **kwargs):
tk.Frame.__init__(self, master, *args, **kwargs)
self._create_widgets()
self._display_widgets()
def _create_widgets(self):
def __create_image_label():
def ___load_images():
self.label.images = list()
self.label.images.append(tk.PhotoImage(file="8.gif"))
self.label.images.append(tk.PhotoImage(file="13.gif"))
self.label = tk.Label(self)
___load_images()
def __create_buttons():
self.buttons = list()
for i in range(2):
self.buttons.append(tk.Button(self, text=i,
command=lambda i=i: self.replace_image(i)))
__create_image_label()
__create_buttons()
def replace_image(self, button_index):
"""
Replaces the image in label attribute based on the index of the
button pressed.
"""
self.label['image'] = self.label.images[button_index]
def _display_widgets(self):
self.label.pack()
for i in range(2):
self.buttons[i].pack(fill='x', expand=True)
if __name__ == '__main__':
#download_images() # comment out after initial run
root = tk.Tk()
frame = ImageFrame(root)
frame.pack()
tk.mainloop()

How to open a new frame from a current window in python tkinter?

class Login:
def __init__(self):
Label1 = Label(root,text = "Username")
Label2 = Label(root,text = "Password")
self.Entry1 = Entry(root)
self.Entry2 = Entry(root,show = "*")
Label1.grid(row=0)
Label2.grid(row=1)
self.Entry1.grid(row = 0,column = 1)
self.Entry2.grid(row = 1,column = 1)
root.minsize(width = 300,height = 80)
##new_window_button = Button(text="new window", command = ????)
##new_window_button.grid(columnspan = 2)
lgbutton = Button(text = "Login",command = self.ButtonClicked)
lgbutton.grid(columnspan = 2)
def ButtonClicked(self):
username = self.Entry1.get()
password = self.Entry2.get()
GetDatabase(username,password)
Currently this is what I have to create a window, however I want it to that when the new_window_button is clicked, the new page has its own widgets. I've used Toplevel before but it creates a child window without the widgets. Instead, the widgets are added to the parent window.
Judging by the comments it looks as though you are struggling with declaring the correct parent for widgets.
When a widget is declared the first parameter passed in to it is it's parent. For example:
Label(root, text="I'm in the root window.")
# ^ This is the parent
As opposed to:
Label(top, text="I'm in the top window.")
# ^ This is the parent
Please see a more fleshed out example below:
from tkinter import *
root = Tk()
top = Toplevel(root)
label1 = Label(root, text="I'm a placeholder in your root window.")
label2 = Label(top, text="I'm a placeholder in your top window.")
label1.pack()
label2.pack()
root.mainloop()
import tkinter
from tkinter import *
class LoginForm(Frame):
def __init__(self,master=None):
super().__init__(master)
self.pack()
self.createWidget()
def createWidget(self):
self.lblEmailId=Label(self,text="Email Id")
self.lblEmailId.grid(row=0,column=0)
self.varEmailid=StringVar()
self.txtEmailId=Entry(self,textvariable=self.varEmailid)
self.txtEmailId.grid(row=0,column=1)
self.txtEmailId.bind("<KeyRelease>",self.key_press)
self.lblPassword = Label(self, text="Password")
self.lblPassword.grid(row=1, column=0)
self.varPassword=StringVar()
self.txtPassword= Entry(self, textvariable=self.varPassword)
self.txtPassword.grid(row=1, column=1)
self.btnLogin=Button(self,text="Login")
self.btnLogin.grid(row=2,column=1)
self.btnLogin.bind("<Button-1>",self.btnLogin_click)
def btnLogin_click(self,event):
self.varPassword.set(self.varEmailid.get())
LoginWindow=Toplevel()
def key_press(self,event):
self.varPassword.set(self.varEmailid.get())
root=Tk()
fromLogin=LoginForm(root)
root.mainloop()

Categories