I have successfully made a 'next' and 'back' button for the firstDicePage and secondDicePage functions so that I could return to either of the pages when needed. However, I am trying to avoid making multiple pages pop up every time I hit those buttons. I heard of .withdraw(), but I am unsure how to apply it in this code.
from tkinter import *
from tkinter import simpledialog
from tkinter import ttk
from tkinter import filedialog
from tkinter.font import Font
import tkinter as tk
import from PIL import Image, ImageTk
import tkinter
import sys
import random
def firstDicePage():
firstWindow = tkinter.Toplevel(window) # Create new window.
firstWindow.title("Dice Roller Generator")
# Change Icon photo
image = PhotoImage(file = "C:\\Users\\alexi\\Desktop\\Project Photos\\Dice logo.png")
firstWindow.iconphoto(False, image)
# Center
app_width = 900
app_height = 600
screen_width = firstWindow.winfo_screenwidth()
screen_height = firstWindow.winfo_screenheight()
x = (screen_width / 2) - (app_width / 2)
y= (screen_height / 2) - (app_height / 2)
firstWindow.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')
Label(firstWindow, text = "\n\nSelect How Many Dice You Want to Roll!", font='Helvetica 16 bold').pack()
img = ImageTk.PhotoImage(Image.open("Dice.png"))
my_label = Label(firstWindow, image=img)
my_label.img = img # Save reference to image.
my_label.pack()
counter = tkinter.IntVar()
def increase():
counter.set(min(10, counter.get() + 1))
def decrease():
counter.set(max(0, counter.get() - 1))
lbl = Label(firstWindow, textvariable = counter, font='Helvetica 16 bold')
lbl.place(x=450, y=330)
btn1 = Button(firstWindow, text="+", font='Helvetica 16 bold', padx = 8, pady = 5, command = increase, fg="dark green", bg = "white")
btn1.place(x=499, y=320)
btn2 = Button(firstWindow, text ="-", font='Helvetica 16 bold', padx = 11.1, pady = 5, command = decrease, fg="dark green", bg = "white")
btn2.place(x=375, y=320)
btn3 = Button(firstWindow, text = "Next", font='Helvetica 16 bold', command=lambda: secondDicePage())
btn3.place(x = 800 , y = 530)
def secondDicePage():
secondWindow = tkinter.Toplevel(window) # Create new window.
secondWindow.title("Dice Roller Generator")
# Change Icon photo
image = PhotoImage(file = "C:\\Users\\alexi\\Desktop\\Project Photos\\Dice logo.png")
secondWindow.iconphoto(False, image)
# Center
app_width = 900
app_height = 600
screen_width = secondWindow.winfo_screenwidth()
screen_height = secondWindow.winfo_screenheight()
x = (screen_width / 2) - (app_width / 2)
y= (screen_height / 2) - (app_height / 2)
secondWindow.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')
btn3 = Button(secondWindow, text = "Back", font='Helvetica 16 bold', command=lambda: firstDicePage())
btn3.place(x = 30 , y = 530)
def secondButton():
# Toplevel object which will
# be treated as a new window
secondWindow = Toplevel(window)
secondWindow.title("Dice Roller Generator")
# Change Icon photo
img = PhotoImage(file = "C:\\Users\\alexi\\Desktop\\Project Photos\\Dice logo.png")
secondWindow.iconphoto(False, img)
# Center
app_width = 600
app_height = 400
screen_width = secondWindow.winfo_screenwidth()
screen_height = secondWindow.winfo_screenheight()
x = (screen_width / 2) - (app_width / 2)
y= (screen_height / 2) - (app_height / 2)
secondWindow.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')
# A Label widget to show in top-level
Label(secondWindow, text = "\n\nSelect What/How Many Dice You Want to Roll!", font='Helvetica 16 bold').pack()
# Create the window(root interface)
window = Tk()
# Create a title
window.title("Dice Roller Generator")
# Change Icon photo
img = PhotoImage(file = "C:\\Users\\alexi\\Desktop\\Project Photos\\Dice logo.png")
window.iconphoto(False, img)
# Center
app_width = 600
app_height = 400
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
x = (screen_width / 2) - (app_width / 2)
y= (screen_height / 2) - (app_height / 2)
window.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')
# Create a label widget
lbl = Label(window, text = "\n\n\nChoose the Kind of Die You Want to Roll", font='Helvetica 16 bold')
#Packing(size), Shove it in the screen
lbl.pack()
btn1 = Button(window, text = "Regular Dice", padx = 15, pady = 15, command = firstDicePage)
btn1.place(x=145, y=130)
btn2 = Button(window, text = "D&D Dice", padx = 20, pady = 15, command = secondButton)
btn2.place(x=355, y=130)
btn3 = Button(window, text="Exit", padx = 15, pady = 5, command = window.quit)
btn3.place(x=275, y=335)
window.mainloop()
Related
I am trying to connect dice png files in a window, but I can not seem to connect the number incrementor that goes up to 10(for 10 images) to align with the said amount of dice. Is there a way to connect them?
This is a define function(firstDicePage()). Asks for the amount of dice you want to roll.
# enables and disables the minus and plus button
def changeMinusState():
if (btn2['state'] == NORMAL):
btn2['state'] = DISABLED
else:
btn2['state'] = NORMAL
def changePlusState():
if (btn1['state'] == NORMAL):
btn1['state'] = DISABLED
else:
btn1['state'] = NORMAL
def increase():
counter.set(min(10, counter.get() + 1))
def decrease():
counter.set(max(0, counter.get() - 1))
lbl = Label(firstWindow, textvariable = counter, font='Helvetica 16 bold')
lbl.place(x=450, y=330)
btn1 = Button(firstWindow, text="+", font='Helvetica 16 bold', padx = 8, pady = 5, command = increase, fg="dark green", bg = "white")
btn1.place(x=499, y=320)
btn2 = Button(firstWindow, text ="-", font='Helvetica 16 bold', padx = 11.1, pady = 5, command = decrease, fg="dark green", bg = "white")
btn2.place(x=375, y=320)
btn4 = Button(firstWindow, text = "Next", font='Helvetica 16 bold', command=lambda: secondDicePage())
btn4.place(x = 800 , y = 530)
btn5 = Button(firstWindow, text = "Select", font ='Helvetica 16 bold', command = lambda: [changeMinusState(), changePlusState()], bg='#ffffff',
activebackground = 'green', padx = 19, pady = 2)
btn5.place(x = 400, y = 385)
This define function connects to the first one. It has the dice.
Updated
def secondDicePage(num_dices):
secondWindow = tkinter.Toplevel(window) # Create new window.
secondWindow.title("Dice Roller Generator")
# Change Icon photo
image = PhotoImage(file = "C:\\Users\\alexi\\Desktop\\Project Photos\\Dice logo.png")
secondWindow.iconphoto(False, image)
# Center
app_width = 900
app_height = 600
screen_width = secondWindow.winfo_screenwidth()
screen_height = secondWindow.winfo_screenheight()
x = (screen_width / 2) - (app_width / 2)
y= (screen_height / 2) - (app_height / 2)
secondWindow.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')
images
dice = ['dice_1.png', 'dice_2.png', 'dice_3.png', 'dice_4.png', 'dice_5.png', 'dice_6.png']
# middle image
img1 = ImageTk.PhotoImage(Image.open("C:\\Users\\alexi\\Desktop\\Project Photos\\questionmark.png"))
lbl1 = Label(secondWindow, image=img1)
lbl1.img = img1 # Save reference to image.
lbl1.pack()
lbl1.place(x = 380 , y = 95)
lbl2 = Label(secondWindow, image=img1)
lbl2.img = img1 # Save reference to image.
lbl2.pack()
lbl2.place(x = 195 , y = 95)
lbl3 = Label(secondWindow, image=img1)
lbl3.img = img1 # Save reference to image.
lbl3.pack()
lbl3.place(x = 565 , y = 95)
lbl4 = Label(secondWindow, image=img1)
lbl4.img = img1 # Save reference to image.
lbl4.pack()
lbl4.place(x = 746 , y = 95)
lbl5 = Label(secondWindow, image=img1)
lbl5.img = img1 # Save reference to image.
lbl5.pack()
lbl5.place(x = 1 , y = 95)
lbl6 = Label(secondWindow, image=img1)
lbl6.img = img1 # Save reference to image.
lbl6.pack()
lbl6.place(x = 380 , y = 300)
lbl7 = Label(secondWindow, image=img1)
lbl7.img = img1 # Save reference to image.
lbl7.pack()
lbl7.place(x = 195 , y =300)
lbl8 = Label(secondWindow, image=img1)
lbl8.img = img1 # Save reference to image.
lbl8.pack()
lbl8.place(x = 565 , y = 300)
lbl9 = Label(secondWindow, image=img1)
lbl9.img = img1 # Save reference to image.
lbl9.pack()
lbl9.place(x = 746 , y = 300)
lbl10 = Label(secondWindow, image=img1)
lbl10.img = img1 # Save reference to image.
lbl10.pack()
lbl10.place(x = 1 , y = 300)
Function for labels
def rolling_dice1():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl1.configure(image = image1, bg = '#B9C6C9')
lbl1.image = image1
def rolling_dice2():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl2.configure(image = image1, bg = '#B9C6C9')
lbl2.image = image1
def rolling_dice3():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl3.configure(image = image1, bg = '#B9C6C9')
lbl3.image = image1
def rolling_dice4():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl4.configure(image = image1, bg = '#B9C6C9')
lbl4.image = image1
def rolling_dice5():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl5.configure(image = image1, bg = '#B9C6C9')
lbl5.image = image1
def rolling_dice6():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl6.configure(image = image1, bg = '#B9C6C9')
lbl6.image = image1
def rolling_dice7():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl7.configure(image = image1, bg = '#B9C6C9')
lbl7.image = image1
def rolling_dice8():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl8.configure(image = image1, bg = '#B9C6C9')
lbl8.image = image1
def rolling_dice9():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl9.configure(image = image1, bg = '#B9C6C9')
lbl9.image = image1
def rolling_dice10():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl10.configure(image = image1, bg = '#B9C6C9')
lbl10.image = image1
widgets
btn1 = Button(secondWindow, text = "Back", font='Helvetica 16 bold', command = secondWindow.destroy)
btn1.place(x = 30 , y = 530)
btn2 = Button(secondWindow, text = "Roll Dice", font='Helvetica 16 bold', command = lambda: [rolling_dice1(), rolling_dice2(), rolling_dice3(), rolling_dice4(), rolling_dice5(), rolling_dice6(), rolling_dice7(), rolling_dice8(),
rolling_dice9(), rolling_dice10()])
btn2.place(x = 400 , y = 30)
I've been running my code on python idle while working on this and didn't receive any problems until I tried running it on visual studio. When running it the tk window just closes and it doesn't go to the classes it tells it too. I am still learning so I probably have some mistakes I would love to get any feedback.
import tkinter as tk
#Takes photos with certain char and if clicked another char program stops
from cv2 import *
import numpy as np
import cv2
import os
from datetime import datetime
now = datetime.now()
time = now.strftime("%H:%M:%S")
#sets the directory and text info
os.chdir(r"C:\Users\asdasd\Desktop\camera")
file_name = 'pic'
cam = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_TRIPLEX
org = (00,300)
fontScale = 1
color = (255,0,0)
thickness = 1
root= tk.Tk()
photo = tk.PhotoImage(file=r"C:\Users\asdas\Desktop\camera\pic.png")
root.iconphoto(False, photo)
root.geometry("+0+50")
print("created window")
#Creates window
canvas1 = tk.Canvas(root, width = 600, height = 600)
canvas1.pack()
canvas1.configure(bg='lightgray')
root.title("ShippingData")
root.lift()
#text label for batch #
label1 = tk.Label(root, text='Enter Batch# :')
label1.config(font=('helvetica', 15))
canvas1.create_window(65, 50, window=label1)
print("created window")
#creates input window for batch #
entry1 = tk.Entry (root)
canvas1.create_window(200, 50, window=entry1)
#text label for initials
label1 = tk.Label(root, text='Enter initials :')
label1.config(font=('helvetica', 15))
canvas1.create_window(65, 100, window=label1)
#creates input window for intials
entry2 = tk.Entry (root)
canvas1.create_window(200, 100, window=entry2)
#gets the info after start button is pressed
def getInfo ():
print("getinfo")
x1 = entry1.get()
x2 = entry2.get()
name = str(x1 + x2)
global dirname
dirname = name
os.mkdir(dirname)
label1 = tk.Label(root, text= "Program Starting")
canvas1.create_window(200, 230, window=label1)
canvas1.destroy()
programStarted()
print("button")
button1 = tk.Button(root, text='Start', command=getInfo)
print("button created")
canvas1.create_window(200, 180, window=button1)
print("canvas created for window")
def programStarted():
print("programstart")
root.update()
#creates new window
global canvas2
canvas2 = tk.Canvas(root, width = 400, height = 300)
canvas2.pack()
# Camera instructions
label2 = tk.Label(root, text= "Press z to take Photos.")
canvas2.create_window(200, 100, window=label2)
label3 = tk.Label(root, text= "Press c multiple times when finished to stop taking photos. ")
canvas2.create_window(200, 150, window=label3)
root.update()
camera()
#camera program
def camera():
print("camera")
global n
global time
global path
n= 1
while(True):
numphoto = "#" + str(n)
ret, frame = cam.read()
cv2.namedWindow("Shipping camera", cv2.WINDOW_NORMAL)
scale_percent = 100 # percent of original size
width = int(frame.shape[1] * scale_percent / 100)
height = int(frame.shape[0] * scale_percent / 100)
dim = (width, height)
frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
scale_percent = 100 # percent of original size
width = int(frame.shape[1] * scale_percent / 100)
height = int(frame.shape[0] * scale_percent / 100)
dim = (width, height)
frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
cv2.putText(frame, numphoto, org, font, fontScale,color,thickness, cv2.LINE_AA, False)
cv2.imshow('Shipping camera', frame)
cv2.setWindowProperty("Shipping camera", cv2.WND_PROP_TOPMOST, 1)
if cv2.waitKey(1) & 0xFF == ord('z'):
n+=1
cv2.imwrite(os.path.join(dirname,(file_name + (str(n-1)) + ".jpg")), frame)
path = (os.path.join(str(r"C:\Users\sadsads\Desktop\camera"), str(dirname)))
elif (cv2.waitKey(1) & 0xFF == ord('c')):
# stops everything
cam.release()
cv2.destroyAllWindows()
with open((path+r'\timelog.txt'), 'w') as f:
f.write(time+ '\n')
now = datetime.now()
time2 = now.strftime("%H:%M:%S")
f.write(time2+ '\n')
y = 0
if(y == 0):
# destory the other windows
root.quit()
root.destroy()
break
else:
root.mainloop()
I am writing again because I have enough problems with grid to center 2 frames. before with .pack it was easier for me but now with grid I can't center my 2 frames in my window, what am I doing wrong??
self.wind = window
self.wind.title('AplicaciĆ³n')
screen_width=self.wind.winfo_screenwidth()
screen_height=self.wind.winfo_screenheight()
x= (screen_width / 2) - (Product.WIDTH /2)
y= (screen_height / 2) - (Product.HEIGHT /2)
self.wind.geometry(f"{Product.WIDTH}x{Product.HEIGHT}+{int(x)}+{int(y)}")
self.wind.resizable(False, False)
frame2 = customtkinter.CTkFrame(self.wind, corner_radius=5)
#frame2.pack(expand="true")
frame2.grid(row=0, sticky="NSEW",pady=(20,20))
self.label_hora = Label(frame2, font = ('calibri', 25, 'bold'),background = 'purple', foreground = 'white')
#self.label_hora.pack(fill=BOTH, expand=1)
self.label_hora.grid(stick="NSEW")
self.tick()
#frame principal
frame = customtkinter.CTkFrame(self.wind, corner_radius=5)
#frame.pack(expand="true")
frame.grid(row=1)
button_llegue = customtkinter.CTkButton(master=frame, corner_radius=8,fg_color="IndianRed3",hover_color="IndianRed4", text='Llegue',command=self.add_fecha_llegue)
button_llegue.grid(row = 0, column = 0,pady=(20,10),padx=(15,15))
button_sali = customtkinter.CTkButton(master=frame, corner_radius=8,fg_color="PaleGreen3",hover_color="PaleGreen4", text='Me Voy',command=self.add_fecha_sali)
button_sali.grid(row = 0, column = 1,pady=(20,10),padx=(15,15))
self.tree = ttk.Treeview(master=frame,height = 10, selectmode="browse")
self.tree.grid(row = 1,column=0,pady=(10,20),columnspan=2,sticky="NWSE",padx=(15,15))
self.tree.heading('#0', text = 'Ultimos registros', anchor = CENTER)
scrollbar = ttk.Scrollbar(frame,orient='vertical',command=self.tree.yview)
scrollbar.grid(row = 1, column=0, sticky="NSE",pady=(10,20),columnspan=2,padx=(0,15))
self.tree.config(yscrollcommand=scrollbar.set)
self.get_fechas()
I'm trying to make sidebar with <Enter> and <Leave> binding and if I move my mouse slower everything works fine, but if I go faster with my mouse the sidebar starts to move back and forth without stopping. Is there a way to fix it?
(Im new with tkinter and python in general)
1/2
2/2
from tkinter import *
#MainWindow
def MainWindow():
global WindowMain
WindowMain = Tk()
WindowMain.config(background="LightGray")
WindowMain.overrideredirect(1)
#MainWindow_size
def Screen_size():
app_width = 1280
app_height = 720
screen_width = WindowMain.winfo_screenwidth()
screen_height = WindowMain.winfo_screenheight()
x = (screen_width / 2) - (app_width / 2)
y = (screen_height / 2) - (app_height / 2)
WindowMain.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')
#Func1
def close(e):
for x in range(1000, 1200):
Blue.place(x=x, y=0)
DarkBlue.place(x=x, y=0)
Blue.update()
DarkBlue.update()
Blue.bind("<Enter>", open)
#Func2
def open(e):
for x in range(-1200, -1000):
Blue.place(x=-x, y=0)
DarkBlue.place(x=-x, y=0)
Blue.update()
DarkBlue.update()
Blue.bind("<Leave>", close)
MainWindow()
Screen_size()
#Label1&2
Blue = Label(WindowMain, background="DeepSkyBlue",
width=70, height=50)
DarkBlue = Label(WindowMain, width=2, height=100,
background="DodgerBlue")
Blue.place(x=1200)
DarkBlue.place(x=1200)
#Buttons
Quit = Button(WindowMain, text="Quit", command=quit,
background="LightSkyBlue").pack()
Move = Button(WindowMain, text="open", command=open,
background="LightSkyBlue", state=DISABLED).pack()
Undo = Button(WindowMain, text="close", command=close,
background="LightSkyBlue", state=DISABLED).pack()
Blue.bind("<Enter>", open)
WindowMain.mainloop()
Your problem will be solved.
I just play around with Blue.update() and Blue.bind. See line
31-31 and 40-41.
In line 31-31 and 40-41, should be outside of looping.
Do not used keyword open and close. Those are valid for Python 3
Modified code:
from tkinter import *
#MainWindow
#def MainWindow():
#global WindowMain
WindowMain = Tk()
WindowMain.config(background="LightGray")
#WindowMain.overrideredirect(1)
#MainWindow_size
def Screen_size():
app_width = 1280
app_height = 720
screen_width = WindowMain.winfo_screenwidth()
screen_height = WindowMain.winfo_screenheight()
x = (screen_width / 2) - (app_width / 2)
y = (screen_height / 2) - (app_height / 2)
WindowMain.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')
#Func1
def _close(e):
for x in range(1000, 1200):
Blue.place(x=x, y=0)
DarkBlue.place(x=x, y=0)
Blue.update()
Blue.bind("<Enter>", _open)
#Func2
def _open(e):
for x in range(-1200, -1000):
Blue.place(x=-x, y=0)
DarkBlue.place(x=-x, y=0)
Blue.update()
Blue.bind("<Leave>", _close)
Screen_size()
#Label1&2
Blue = Label(WindowMain, background="DeepSkyBlue",
width=70, height=50)
DarkBlue = Label(WindowMain,width=2, height=100,
background="DodgerBlue")
Blue.place(x=1200)
DarkBlue.place(x=1200)
#Buttons
Quit = Button(WindowMain, text="Quit", command=quit,
background="LightSkyBlue").pack()
Move = Button(WindowMain, text="open", command=_open,
background="LightSkyBlue", state=DISABLED).pack()
Undo = Button(WindowMain, text="close", command=_close,
background="LightSkyBlue", state=DISABLED).pack()
Blue.bind("<Enter>", _open)
WindowMain.mainloop()
Screenshot before mouse moved:
Screenshot After mouse moved:
I'm currently writing a library system and, in order to better understand how to change between frames, have so far have written code for a screen the user is met with when they first use the program as shown below:
import tkinter as tk
import json
window = tk.Tk() # creates a window
width = 474 # sets the width and height of the screen
height = 266
screen_width = window.winfo_screenwidth() # finds the width of the user's screen
screen_height = window.winfo_screenheight()
center_x = int(screen_width / 2 - width / 2)
center_y = int(screen_height / 2 - height / 2)
window.geometry(f'{width}x{height}+{center_x}+{center_y}') # sets the width, height, and positioning of the window
window.title("Library System") # sets title of window
window.resizable(False, False) # Prevents the window being resized by both the x and y coordinates
welcome = tk.Frame(width=200, height=200, background="light cyan")
ChangeInfo = tk.Frame(window, width=400, height=200)
ChangeInfo.pack(fill='both', expand=True, padx=0, pady=0)
def WelcomeScreen():
greeting = tk.Label(welcome, text="Welcome", font=("comic sans", 15), bg ='light cyan') # creates a lable with text
greeting.pack()
explaination = tk.Label(welcome, text="This is your first time using this program so please click the button below to "
"enter in \n the username "
"and password you will be using to log into the system in the future"
"", font=("comic_sans", 9), bg="light cyan")
explaination.place(x = (width)/2, y= 50, anchor='center')
login_button = tk.Button(welcome, text="Set username and password", height=3, width=22,
font=("comic_sans", 10), bg = "turquoise")
login_button.place(x= width / 2, y= height / 2, anchor='center')
window.mainloop()
WelcomeScreen()
The only thing that is displayed at the moment is the window and its title. How do I display the frame instead of only the window?
If you want to show the welcome frame initially, you need to call welcome.pack(...) instead of ChangeInfo.pack(...).