Perceive Key in Python Window - python

I make a program that choose a picture in pythons window and enter a key, then the size of picture will be double in size. But when I enter the key, the program is going to stop. And window of python is closed.
How can I make it work?
I think part of keyEvent makes errors.
from tkinter import *
from tkinter.filedialog import*
import keyboard
def func_open():
global filename
filename = askopenfilename(parent = window, filetypes = (("GIF 파일", "*gif"), ("모든 파일", "*.*")))
photo = PhotoImage(file = filename)
pLabel.configure(image = photo)
pLabel.image = photo
def func_exit():
window.quit()
window.destroy()
def keyEvent(event):
global photo
if keyboard.read_key() == "up":
photo = PhotoImage(file = filename)
photo = photo.zoom(2, 2)
pLabel.configure(image = photo)
pLabel.image = photo
window = Tk()
window.geometry("500x500")
window.title("명화 감상하기")
window.bind("<Key>", keyEvent)
photo = PhotoImage()
pLabel = Label(window, image = photo)
pLabel.pack(expand = 1, anchor = CENTER)
mainMenu = Menu(window)
window.config(menu = mainMenu)
fileMenu = Menu(mainMenu)
mainMenu.add_cascade(label = "파일", menu = fileMenu)
fileMenu.add_command(label = "파일 열기", command = func_open)
fileMenu.add_separator()
fileMenu.add_command(label = "프로그램 종료", command = func_exit)
window.bind("<Key>", keyEvent)
window.mainloop()
Output
nothing work
Expected
the picture will grow up twice

Related

TKINTER keep on getting the error "pyimage4 not found", the image is the right file format, it works when only the problem function is on another file

I am making a witcher themed combat game for school, and wanted to incorporate an exit confirmation screen.
To do this, I made a button that calls a function called exit_confirmation.
I decided to add a background image to this function, however it will give the error "pyimage4 not found", if I try to change the image to something that I have used before, it will just say "pyimage{number here} not found".
CLARIFICATION: the problem function is exit_confirmation()
from tkinter import *
import random
root = Tk()
#defining the images
background = PhotoImage(file = 'background.png')
win_screen_image = PhotoImage(file = 'win_screen.png')
lose_screen_image = PhotoImage(file = 'lose_screen.png')
exit_confirmation_image = PhotoImage(file = 'exit_confirmation.gif')
def quit_game():
exit.destroy
root.destroy
#work in progress
def exit_confirmation():
global exit
exit = Tk()
confirmtation_canvas = Canvas(exit, height = 202, width = 360)
confirmtation_canvas.pack()
confirmtation_canvas.create_image(0, 0, image = exit_confirmation_image, anchor = 'nw')
exit.mainloop()
#function to call the intro canvas
def introduction_canvas():
#creates the canvas
c = Canvas(root, height = 720, width = 1280)
c.pack()
#places the background image
c.create_image(0, 0, image = background, anchor = 'nw')
#creates the introduction text
intro_text = c.create_text(240, 80, font = 'Calibri 18', fill = 'white', text = ' Welcome, Witcher\nPlease Enter Your Name:', )
#creates the name input
name = StringVar()
name_entry = Entry(root, textvariable = name, font = 'Calibri 16')
create_name_entry = c.create_window(238, 136, window = name_entry)
#button to move on and confirm the name
confirm_button = Button(c, text = 'Confirm', command = rules_canvas, font = 'Calibri 18')
create_confirm_button = c.create_window(0, 0, window = confirm_button)
#button to quit the game
quit_button = Button(c, text = 'Quit', command = exit_confirmation, font = 'Calibri 18')
create_quit_button = c.create_window(100, 100, window = quit_button)
def rules_canvas():
pass
def game_canvas():
pass
introduction_canvas()
root.mainloop()
I tried using a different IDE, on a different file, changing the file format to .gif from .png, nothing works :/

How to attach delete function in Tkinter GUI

I am new to python & requesting help from experts in this community. I am trying to delete images from my Tkinter widget FrameLabel. I have followed many solutions provided on the StackOverflow, but unfortunately, I am unable to implement those solutions in my code. I need help in deleting the image I have uploaded on the window.
GUI working:
Click on Select
Browse the image
Upload the image
It will display in the LabelFrame shown as following:
frame3 = tk.LabelFrame(pw_right, bd=2, text='Uploaded images')
frame3.pack(side='left', anchor='nw')
Delete Button
DelButton = tk.Button(frame1, text ='Delete', command = button.on_click_del_button)
DelButton.grid(row=0, column=4)
Delete Function:
def on_click_del_button(self):
print('Delete button clicked')
image = self.paths[self.radio_var.get()]
if os.path.exists(image):
os.remove(image)
else:
print("The file does not exist")
Help required section: I need help in defining Delete Function i.e button.on_click_del_button
so that when I press delete. Tkinter deletes the selected image from the window.
Below is the GUI for the window:
I followed the suggestion followed by expert furas, But nothing is happening in the Tkinter window. Although all the print values are being displayed.
You don't have to load image to delete from disk - you need only path
image = self.paths[self.radio_var.get()]
and you have to use variable image, not string "image"
BTW: you don't need lambda to assing this function
command=button.on_click_del_button
and you don't need path='None', image='None' if you don't send values as arguments.
def on_click_del_button(self):
print('Delete button clicked')
image = self.paths[self.radio_var.get()]
if os.path.exists(image):
os.remove(image)
else:
print("The file does not exist")
To hide widget from window you have widget.pack_foger() and widget.grid_forget(). It hides so you can show it again using widget.pack() or widget.grid(...).
To remove widget from window and from memory - so you can't use it again - you have widget.destroy() like
self.radio_handle[0].destroy()
but you would have to know which radiobutton was selected 0, 1 or 2.
Maybe better use path to keep elements in dictionary, not on list
self.radio_handle[path] = radio_button
and later in on_click_del_button
self.radio_handle[path].destroy()
You could also use path as value in Radiobutton
tk.Radiobutton(..., value=path)
EDIT: It remove image from window.
I use StringVar() instead of IntVar()
self.radio_var = tk.StringVar()
and assign path as value in Radiobutton
Radiobutton(..., value=path)
so now it can return path instead of numer and it can be easier to find object in dictionary
self.radio_handle = dict()
Using list and numbers it could be problem because after removing element from list other elements change position on list and it could make problem.
Now I can add widget to dictionary
self.radio_handle[path] = (radio_button)
and the same way I can destroy it
def on_click_del_button(self):
print('Delete button clicked')
path = self.radio_var.get()
self.radio_handle[path].destroy()
import os
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
import cv2
from PIL import Image
from PIL import ImageTk
class Button:
def __init__(self, root, frame3):
self.root = root
self.frame3 = frame3
self.radio_var = tk.StringVar()
self.path_selected = '' # or None
self.paths = []
self.radio_handle = dict()
self.check_value = []
def on_click_select_button(self, fname_label):
print('select button clicked')
fileType = [('jpg/png file', ('*.jpg', '*.png'))]
self.path_selected = filedialog.askopenfilename(filetypes=fileType)
fname_label['text'] = os.path.basename(self.path_selected)
def on_click_upload_button(self, path='None', image='None'):
print('upload button clicked')
if path == 'None':
path = self.path_selected
else:
cv2.imwrite(path, image)
if path in self.paths:
messagebox.showerror('Upload Error', '"'
+ path
+ '"' + ' is already uploaded.')
else:
self.paths.append(path)
self.create_radio_button(path)
def on_click_show_button(self, method):
print('showButton clicked')
image = cv2.imread(self.paths[self.radio_var.get()])
file_name = os.path.basename(self.paths[self.radio_var.get()])
name, ext = os.path.splitext(file_name)
path = 'images/' + name + '_' + method + ext
def create_radio_button(self, path):
image = cv2.imread(path)
# image = cv2.resize(image,(120,120))
image = self.scale_to_height(image, 120)
image_tk = self.to_tk_image(image)
radio_button = tk.Radiobutton(self.frame3, image=image_tk,
value=path,
variable=self.radio_var)
self.radio_var.set('')
self.radio_handle[path] = (radio_button)
self.check_value.append(self.radio_var)
radio_button.grid(row=(len(self.radio_handle) - 1) // 3,
column=(len(self.radio_handle) - 1) % 3)
self.root.mainloop()
def to_tk_image(self, image_bgr):
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
image_pil = Image.fromarray(image_rgb)
image_tk = ImageTk.PhotoImage(image_pil)
return image_tk
def on_click_del_button(self):
print('Delete button clicked')
path = self.radio_var.get()
if path:
self.radio_handle[path].destroy() # remove widget from window
del self.radio_handle[path] # remove from dictionary
self.paths.remove(path) # remove path from list
self.radio_var.set('')
else:
print('Not selected')
#image = path # self.paths[self.radio_var.get()]
#if os.path.exists(image):
# os.remove(image)
#else:
# print("The file does not exist")
def scale_to_height(self, img, height):
scale = height / img.shape[0]
return cv2.resize(img, dsize=None, fx=scale, fy=scale)
if __name__ == '__main__':
os.makedirs('images', exist_ok=True)
root = tk.Tk()
root.title('Image GUI')
root.geometry('1280x960')
pw_left = tk.Frame(root, relief='ridge', borderwidth=4)
pw_left.pack(side='left', anchor='nw')
pw_right = tk.Frame(root, relief='ridge', borderwidth=4)
pw_right.pack(side='left', anchor='nw')
frame1 = tk.Frame(pw_left, bd=2, relief="ridge")
frame1.pack()
frame2 = tk.LabelFrame(pw_left, bd=2, relief="ridge", text='options')
frame2.pack(anchor='nw')
frame3 = tk.LabelFrame(pw_right, bd=2, text='Uploaded images')
frame3.pack(side='left', anchor='nw')
button = Button(root, frame3)
# add label
label = tk.Label(frame1, text='File:')
label.grid(row=0, column=0)
# label to show file name
file_name_label = tk.Label(frame1, text='-----not selected-----', width=20, bg='white')
file_name_label.grid(row=0, column=1)
# file select button
select_button = tk.Button(frame1, text='select',
command=lambda: button.on_click_select_button(file_name_label))
select_button.grid(row=0, column=2)
# upload button
uploadButton = tk.Button(frame1, text='Upload',
command=lambda: button.on_click_upload_button())
uploadButton.grid(row=0, column=3)
DelButton = tk.Button(frame1, text='Delete', command=button.on_click_del_button)
DelButton.grid(row=0, column=4)
root.mainloop()

I can't Manage to close from in Python 3 with tkinter

I am trying to build a xml parser in python, i start to build gui framework, and here i need to create some forms to save some settings values. I manage to make it work and save some values to txt files for startup. But what ever i tried i can't manage to close the settings form when i click button. i need to close it with the x on the window. i can't find the root of the issue.
what i am trying to do is, when i click Cancel, form will be closed. if i click Save, form will first save data then close.
thanks a lot for your supports.
my code is as follows:
try:
# for Python2
print ("Importing for py2");
from Tkinter import * ## notice capitalized T in Tkinter
import tkFileDialog
except ImportError:
# for Python3
print ("Importing for py2 Failed !!!!");
print ("Importing for py3");
from tkinter import *
from tkinter import filedialog
from tkinter.scrolledtext import ScrolledText
from tkinter import messagebox
mainform = Tk()
mainform.minsize(300,100)
mainform.geometry('{}x{}'.format(800, 600))
mainform.title("OVF Template Parser - By Gurhan Cagin (R) 2018")
textPad = ScrolledText(mainform, width=100, height=80)
textPad.pack()
## functions and procdures
def donothing():
x = 0
def quit():
if messagebox.askokcancel("Quit", "Do you really want to quit?"):
exit()
def about_command():
label = messagebox.showinfo("About", "Nokia OVF Template Parser \nCopyright 2018 \nNo rights left to reserve")
def open_command():
file = filedialog.askopenfile(parent=mainform, mode='rb', title='Select a file')
if file != None:
contents = file.read()
textPad.insert('1.0',contents)
file.close()
def SettingsFormFxn():
settingsForm = Tk()
settingsForm.minsize(300,100)
settingsForm.geometry('{}x{}'.format(750, 550))
settingsForm.title("Settings for the devault values")
## Frames
top_frame = Frame(settingsForm, width = 740, height = 50, pady = 3)
bottom_frame = Frame(settingsForm, width = 740, height = 50, pady = 3)
settingsForm.grid_rowconfigure(1, weight=1)
settingsForm.grid_columnconfigure(0, weight=1)
top_frame.grid(row=0, sticky="ew")
bottom_frame.grid(row = 4, sticky = "e")
b1 = Label(top_frame, text = "CPU per Core in Ghz:")
b1.grid(row = 0, column = 0)
entryText = StringVar(settingsForm, "2.1")
e1 = Entry(top_frame, textvariable = entryText, width = 5)
e1.grid(row = 0, column = 2)
def SaveFxn():
with open("settings.txt", "w") as f:
f.write(e1.get() + "\n")
##f.write(ent2.get() + "\n")
def CancelFxn():
settingsForm.destroy
cancel = Button(bottom_frame, text = "Cancel", command = CancelFxn, pady = 10, padx = 10,activebackground='grey',activeforeground='#AB78F1',bg='#e87474',highlightcolor='red')
cancel.grid(row = 0, column = 10)
save = Button(bottom_frame, text = "Save", command = SaveFxn, pady = 10, padx = 10)
save.grid(row = 0, column = 11)
settingsForm.mainloop()
## EOF FXNS
## Menu Definitions
menubar = Menu(mainform)
## File Menu
filemenu = Menu(menubar, tearoff = 0)
filemenu.add_command(label = "Open", command = open_command)
filemenu.add_separator()
filemenu.add_command(label="Exit", command = quit)
menubar.add_cascade(label="File", menu=filemenu)
## Settings Menu
settingsmenu = Menu(menubar, tearoff = 0)
settingsmenu.add_command(label = "Settings", command = SettingsFormFxn)
menubar.add_cascade(label="Settings",menu=settingsmenu)
## About Menu
aboutmenu = Menu(menubar, tearoff = 0)
aboutmenu.add_command(label = "About", command = about_command)
menubar.add_cascade(label="Help", menu=aboutmenu)
mainform.config(menu=menubar)
## EOF Menu Definitions
## Main loop
mainloop()
You forgot your parenthesis when trying to call settingsForm.destroy.
def CancelFxn():
settingsForm.destroy()

(Tkinter) Image won't show up in new window

I just started using python tkinter and I have a button that opens a new window. One the new window there is an image, but the image won't show up.Can you please help me solve my problem?
from tkinter import *
def nwindow():
nwin = Toplevel()
nwin.title("New Window")
btn.config(state = 'disable')
photo2 = PhotoImage(file = 'funny.gif')
lbl2 = Label(nwin, image = photo2)
lbl2.pack()
def quit():
nwin.destroy()
btn.config(state = 'normal')
qbtn = Button(nwin, text = 'Quit', command = quit)
qbtn.pack()
main = Tk()
main.title("Main Window")
main.geometry("750x750")
photo = PhotoImage(file = 'funny.gif')
lbl = Label(main, image = photo)
lbl.pack()
btn = Button(main, text = "New Winodw", command = nwindow)
btn.pack()
main.mainloop()
your coding doesn't work but putting .mainloop() should fix your issue
def nwindow():
nwin = Toplevel()
nwin.title("New Window")
btn.config(state = 'disable')
photo2 = PhotoImage(file = 'funny.gif')
lbl2 = Label(nwin, image = photo2)
lbl2.pack()
nwin.mainloop()

music player playlist

i made a music player with a playlist but the songs in playlist are not playable because only the name of song is going in playlist not a complete mp3 file. can you tell me how to handle this problem??
here is my code:
from Tkinter import *
import mp3play
import tkFileDialog
import Tkinter
import tkFont
import Tkinter as tk
#from PIL import ImageTk,Image
def open_file(): #Opens a dialog box to open .mp3 file
global music #then sends filename to file_name_label.
global mp3
global play_list
filename.set (tkFileDialog.askopenfilename(defaultextension = ".mp3", filetypes=[("All Types", ".*"), ("MP3", ".mp3")]))
playlist = filename.get()
playlist_pieces = playlist.split("/")
play_list.set (playlist_pieces[-1])
playl = play_list.get()
play_list_display.insert(END, playl)
mp3 = filename.get()
print mp3
music = mp3play.load(mp3)
pieces = mp3.split("/")
name.set (pieces[-1])
def play(): #Plays the .mp3 file
music.play()
def stop(): #Stops the .mp3 file
music.stop()
def pause(): #Pauses or unpauses the .mp3 file
if music.ispaused() == True:
music.unpause()
elif music.ispaused() == False:
music.pause()
def vol(event): #Allows volume to be changed with the slider
v = Scale.get(volume_slider)
music.volume(v)
def tune_changed(event):
idx = event.widget.curselection()[0]
print ("Now playing %s" % event.widget.get(idx))
def Exit():
exit()
root = tk.Tk()
root.title("EmoPlayer")
root.configure(background='black')
#root = Tk()
root.geometry('300x100+750+300')
filename = Tkinter.StringVar()
name = Tkinter.StringVar()
play_list = Tkinter.StringVar()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0, bg="black", fg="Orange")
menubar.add_cascade(label='File', menu = filemenu)
filemenu.add_command(label='Open', command = open_file)
filemenu.add_separator()
filemenu.add_command(label='Exit', command = Exit)
root.config(menu=menubar)
open_file = Button(root, width = 6, height = 1, text = 'Mood',fg='Orange', bg='black')
open_file.grid(row=0, column=3)
play_button = Button(root, width = 5, height = 1, text='Play', fg='Orange', command = play, bg="black")
play_button.grid(row=0, column=0, sticky = W)
stop_button = Button(root, width = 5, height = 1, text='Stop',fg='Orange', command = stop, bg="black")
stop_button.grid(row=0, column=1, sticky = W)
pause_button = Button(root, width = 5, height = 1, text='Pause',fg='Orange', command = pause, bg="black")
pause_button.grid(row=0, column=2)
volume_slider = Scale(root, label='Volume', orient = 'horizontal', fg = 'Orange', command = vol, bg="black")
volume_slider.grid(row=0, column=4)
file_name_label = Label(root, font=('Comic Sans', 8), fg = 'Orange', wraplength = 300, textvariable=name, bg="black" )
file_name_label.grid(row=3, column=0, columnspan=8)
play_list_window = Toplevel(root, height = 150, width = 100)
play_list_window.title("Playlist")
play_list_display = Listbox(play_list_window, selectmode=EXTENDED, width = 50, bg="Dark Slate grey", fg="Orange")
play_list_display.bind("<Double-Button-1>", tune_changed)
play_list_display.pack()
play_list_window.mainloop()
root.mainloop()
I had a look at your code because I haven't worked with mp3play before and thought it was interesting.
Here's what I changed:
I put your code in a class so that it's easier and cleaner to share variables between methods. It also removes the need to mess around with global. Generally cleaned up the code a bit, for example, breaking up excessively long lines. I tried not to change your code where it wasn't necessary though.
Added a trackLocations list that keeps the actual file paths.
Added a line that loads the new file on double clicking in the playlist
This was the result, I hope it helps:
from Tkinter import *
import mp3play
import tkFileDialog
import Tkinter
import tkFont
import Tkinter as tk
class musicplay:
def __init__(self):
self.music = None
self.play_list = []
self.trackLocations = []
self.root = tk.Tk()
self.root.title("EmoPlayer")
self.root.configure(background='black')
self.root.geometry('300x100+750+300')
self.filename = Tkinter.StringVar()
self.name = Tkinter.StringVar()
self.play_list = Tkinter.StringVar()
menubar = Menu(self.root)
filemenu = Menu(menubar, tearoff=0, bg="black", fg="Orange")
menubar.add_cascade(label='File', menu = filemenu)
filemenu.add_command(label='Open', command = self.open_file)
filemenu.add_separator()
filemenu.add_command(label='Exit', command = self.Exit)
self.root.config(menu=menubar)
open_file = Button(self.root, width = 6, height = 1,
text = 'Mood',fg='Orange', bg='black')
open_file.grid(row=0, column=3)
play_button = Button(self.root, width = 5, height = 1, text='Play',
fg='Orange', command = self.play, bg="black")
play_button.grid(row=0, column=0, sticky = W)
stop_button = Button(self.root, width = 5, height = 1, text='Stop',
fg='Orange', command = self.stop, bg="black")
stop_button.grid(row=0, column=1, sticky = W)
pause_button = Button(self.root, width = 5, height = 1, text='Pause',
fg='Orange', command = self.pause, bg="black")
pause_button.grid(row=0, column=2)
self.volume_slider = Scale(self.root, label='Volume',
orient = 'horizontal', fg = 'Orange',
command = self.vol, bg="black")
self.volume_slider.grid(row=0, column=4)
file_name_label = Label(self.root, font=('Comic Sans', 8),
fg = 'Orange', wraplength = 300,
textvariable=self.name, bg="black")
file_name_label.grid(row=3, column=0, columnspan=8)
play_list_window = Toplevel(self.root, height = 150, width = 100)
play_list_window.title("Playlist")
self.play_list_display = Listbox(play_list_window, selectmode=EXTENDED,
width = 50, bg="Dark Slate grey",
fg="Orange")
self.play_list_display.bind("<Double-Button-1>", self.tune_changed)
self.play_list_display.pack()
play_list_window.mainloop()
self.root.mainloop()
def open_file(self):
"""
Opens a dialog box to open .mp3 filemusic,
then sends filename to file_name_label.
"""
self.filename.set(tkFileDialog.askopenfilename(
defaultextension = ".mp3",
filetypes=[("All Types", ".*"), ("MP3", ".mp3")]))
self.playlist = self.filename.get()
playlist_pieces = self.playlist.split("/")
self.play_list.set (playlist_pieces[-1])
playl = self.play_list.get()
self.play_list_display.insert(END, playl)
print self.filename.get()
self.music = mp3play.load(self.filename.get())
pieces = self.filename.get().split("/")
self.trackLocations += [self.filename.get()]
self.name.set(pieces[-1])
def play(self):
"""Plays the .mp3 file"""
self.music.play()
def stop(self):
"""Stops the .mp3 file"""
self.music.stop()
def pause(self):
"""Pauses or unpauses the .mp3 file"""
if self.music.ispaused():
self.music.unpause()
else:
self.music.pause()
def vol(self, event):
"""Allows volume to be changed with the slider"""
v = Scale.get(self.volume_slider)
try:
self.music.volume(v)
except:
pass
def tune_changed(self, event):
idx = event.widget.curselection()[0]
self.music = mp3play.load(self.trackLocations[int(idx)])
print ("Now playing %s" % event.widget.get(idx))
def Exit(self):
exit()
if __name__ == "__main__":
musicplay()
ValueError: invalid literal for int() with base 10: 'The specified device is not open or is not recognized by MCI.'
I also struggled with this error after long google search i found on some German forum a post from some c++ guy who said it was because of ID3v2 tags with witch MCI has problems.
I then used mutagen - Python multimedia tagging library, to strip the tag from mp3 before playing it, since then i never encountered this error again. Also if resorting to mutagen make sure the mp3 file has write permission before stripping of its tag.

Categories

Resources