I made a program that converts 1 currency to another(in this case only won to dollars). However, when I try to click on US radio button, it says "could not convert string to float: '' ". So, what's the problem here? I tried to run it without an additional window, and it worked perfectly fine, but when I open a converter window in a new window, it does not work. What is the problem and how do I make it so the converter would work fine when you open it in a new window?
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showerror
from tkinter import *
root = tk.Tk()
root.geometry('5000x5000')
def openconverter():
root = tk.Tk()
root.title('Change Converter')
root.geometry('400x210')
def won_to_dollar(f):
US = 0.00079
return f*US
frame = ttk.Frame(root)
options = {'padx': 5, 'pady': 5}
won = tk.StringVar()
won_entry = ttk.Entry(frame, textvariable=won)
won_entry.grid(column=1, row=0, **options)
def convert_button_clicked(won_to_dollar):
try:
f = float(won.get())
c = won_to_dollar(f)
result = f'{f} won = {c:.2f}'
result_label.config(text=result)
except ValueError as error:
showerror(title='Error', message=error)
result_label = ttk.Label(frame)
result_label.grid(row=1, columnspan=3, **options)
frame.grid(padx=10, pady=10)
r = IntVar()
Radiobutton(root, text="US", variable = r, value = 1, command = lambda : convert_button_clicked(won_to_dollar)).place(x = 220, y = 20)
myLabel = Label(root, text = r.get())
myLabel.grid
root.mainloop()
Converted = Button(root, text="converter",font = ("Helvetica", 15), width=50, height=50, compound="c", activeforeground = "green", command = lambda: openconverter())
Converted.place(x=10, y=185)
root.mainloop()
Try this and click convert and enter value and select US.
from tkinter import ttk
from tkinter.messagebox import showerror
from tkinter import *
root = Tk()
root.title('Change Converter')
root.geometry('400x810')
def openconverter():
def won_to_dollar(f):
US = 0.00079
return f*US
frame = Frame(root)
options = {'padx': 5, 'pady': 5}
won = StringVar()
won_entry = Entry(frame, textvariable=won)
won_entry.grid(column=1, row=0, **options)
def convert_button_clicked(won_to_dollar):
try:
f = won.get()
c = won_to_dollar(float(f))
result = f'{f} won = {c}'
result_label.config(text=result)
except ValueError as error:
showerror(title='Error', message=error)
result_label = Label(frame)
result_label.grid(row=1, columnspan=3, **options)
frame.grid(padx=10, pady=10)
r = IntVar()
Radiobutton(root, text="US", variable = r,
value = 1,
command = lambda : convert_button_clicked(won_to_dollar)).place(x = 220, y = 20)
myLabel = Label(root, text = r.get())
myLabel.grid
Converted = Button(root, text="converter",
font = ("Helvetica", 15), width=50, height=50, compound="c",
activeforeground = "green", command = lambda: openconverter())
Converted.place(x=10, y=5)
root.mainloop()
Related
Not really sure what im doing in this stage tbh, found someone asking a similar thing and tried to include it. However im not sure how to integrate it and at the moment they both do their own tkinter windows. One saving a .txt file, the other producing what ive written.
import sys
import tkinter as tk
from tkinter import *
from tkinter.messagebox import showinfo
root = tk.Tk()
root.wm_title('QR Code Generator')
def login():
frame = Frame(root)
Label(frame, text = "Welcome to QR Code Generator").grid(row = 0)
Label(frame, text = "Enter the link you want as a QR Code ").grid(row = 1)
e1 = Entry(frame)
e1.grid(row=1, column = 1)
Button(frame, text = 'Continue', command = save).grid(row = 4, column = 1, sticky = W, pady = 4)
return frame
def save():
file_name = entry.get()
with open(file_name + '.txt', 'w') as file_object:
file_object.write(file_name)
if __name__ == '__main__':
top = tk.Tk()
entry_field_variable = tk.StringVar()
entry = tk.Entry(top, textvariable=entry_field_variable)
entry.pack()
tk.Button(top, text="save", command=save).pack()
login_frame = login()
login_frame.pack(fill="both", expand=True)
root.mainloop()
wanting the "paste link for qr code" section to be saved into a .txt
Your filename is not defined anywhere in the code
I.e. your filename is empty, this results in a file with no name '.txt'
def save():
file_name = entry.get()
with open(file_name + '.txt', 'w') as file_object:
file_object.write(file_name)
Your code opens two windows, it is being created in this line, whenever you define another instance of Tk() it will be a new window, if you need it, I recommend Toplevel
if __name__ == '__main__':
top = tk.Tk()
Try something cleaner and easier to understand
import tkinter as tk
from tkinter import *
root = tk.Tk()
root.wm_title('QR Code Generator')
def save():
content = e1.get()
with open('your_file.txt', 'w') as file_object:
file_object.write(content)
frame = Frame(root)
frame.pack()
Label(frame, text="Welcome to QR Code Generator").pack()
Label(frame, text="Enter the link you want as a QR Code ").pack()
e1 = Entry(frame)
e1.pack()
Button(frame, text='Continue', command=save).pack()
if __name__ == '__main__':
root.mainloop()
The qrcode is created as a picture. You can write a picture as base64 encoded to a text file, but I recommend to save the picture as an image.
I understood your request as "create" and "show" the saved picture into a tkinter window. I saved the picture with a timestamp.
My prototype:
import tkinter as tk
import qrcode
from PIL import ImageTk, Image
import time
root = tk.Tk()
root.title('QR Code Generator')
root.geometry("450x420")
#root.state("zoomed") whole display size
root.config(bg="#2c3e50")
#root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
def create_QR(link_input):
print(link_input.get())
lnk = link_input.get()
global qr_img
qr = qrcode.QRCode(version=1, error_correction = qrcode.constants.ERROR_CORRECT_L, box_size=10, border=3)
qr.add_data(lnk)
qr.make(fit=True)
time_str = str(int(time.time()))
img = qr.make_image(fill_color='cyan', back_color='#2c3e50')
img.save(f'qrcode_{time_str}.png')
qr_img = f'qrcode_{time_str}.png'
return qr_img
def show_qr():
global qr_img
qr_img = ImageTk.PhotoImage(Image.open(qr_img))
qr = tk.Label(frame, image = qr_img)
qr.grid(row =3, columnspan = 3, padx = 5, pady = 5)
qr.config(image = qr_img)
return qr_img
l1 = tk.Label(root, text = "Welcome to QR Code Generator", font=("Calibre", 16), bg="#2c3e50", fg="white")
l1.grid(row =0, columnspan = 2, padx = 5, pady = 5)
frame = tk.Frame(root)
frame.grid()
frame.config(bg="#2c3e50")
l2 = tk.Label(frame, text = "Link you want as a QR Code: ", bg="#2c3e50", fg="white")
l2.grid(row =1, column = 1, padx = 5, pady = 5, sticky="w")
link_name = tk.StringVar(frame, value='hhtps://')
e1 = tk.Entry(frame, textvariable = link_name, width=35)
e1.grid(row =1, column = 2, padx = 5, pady = 5)
b_cre = tk.Button(frame, text = 'Create QR Code', command = lambda: create_QR(link_name))
b_cre.grid(row =2, column = 1, padx = 5, pady = 5)
b_sav = tk.Button(frame, text = 'Show QR Code', command = show_qr)
b_sav.grid(row =2, column = 2, padx = 5, pady = 5)
root.mainloop()
Output:
from tkinter import *
def c_to_f(celsius):
return str(float(celsius) * 1.8 + 32)
window = Tk()
f = Label(window, text="ºF")
f.pack()
finpt = Entry(window)
fvalue = finpt.get()
finpt.pack()
c = Label(window, text="ºC")
c.pack()
cinpt = Entry(window)
cvalue = cinpt.get()
cinpt.pack()
to_f = Button(window, text="Nach ºF umrechnen", command=finpt.insert(0, f"{c_to_f(cvalue)}"))
to_f.pack()
window.mainloop()
After pressing the button, I want to return the show the result of c_to_f(cvalue) in Label c. How can I manage that?
It is better to create another function for the button to_f and do the conversion and show result inside that function:
from tkinter import *
def c_to_f(celsius):
return str(float(celsius) * 1.8 + 32)
def convert_to_fahrenheit():
try:
f = c_to_f(cinpt.get())
finpt.delete(0, END)
finpt.insert(END, f)
except ValueError as ex:
print(ex)
window = Tk()
f = Label(window, text="ºF")
f.pack()
finpt = Entry(window)
#fvalue = finpt.get()
finpt.pack()
c = Label(window, text="ºC")
c.pack()
cinpt = Entry(window)
#cvalue = cinpt.get()
cinpt.pack()
to_f = Button(window, text="Nach ºF umrechnen", command=convert_to_fahrenheit)
to_f.pack()
window.mainloop()
Your code is giving too much problem.
Try this:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title('Temperature Converter')
root.geometry('300x70')
root.resizable(False, False)
def fahrenheit_to_celsius(f):
""" Convert fahrenheit to celsius
"""
return (f - 32) * 5/9
frame = ttk.Frame(root)
options = {'padx': 5, 'pady': 5}
temperature_label = ttk.Label(frame, text='Fahrenheit')
temperature_label.grid(column=0, row=0, sticky='W', **options)
temperature = tk.StringVar()
temperature_entry = ttk.Entry(frame, textvariable=temperature)
temperature_entry.grid(column=1, row=0, **options)
temperature_entry.focus()
def convert_button_clicked():
f = float(temperature.get())
c = fahrenheit_to_celsius(f)
result = f'{f} Fahrenheit = {c:.2f} Celsius'
result_label.config(text=result)
convert_button = ttk.Button(frame, text='Convert')
convert_button.grid(column=2, row=0, sticky='W', **options)
convert_button.configure(command=convert_button_clicked)
result_label = ttk.Label(frame)
result_label.grid(row=1, columnspan=3, **options)
frame.grid(padx=10, pady=10)
root.mainloop()
Screenshot:
I've made this converter. I want it to convert decimal values into binary and hexadecimal using Tkinter..
I made a text input box but I don't know how to get the input values from the input box.
We aren't supposed to use OOP so we can't use classes.
Here is my code (it's in french for some parts) :
import tkinter as tk
from tkinter import *
def ConverterWind():
convertisseur = Tk()
convertisseur.title("Convertisseur")
inputZone = Text(convertisseur, height=2, width=50)
inputZone.pack()
getTextArea = Button(convertisseur, text = "Convertir !", command = getText)
getTextArea.pack()
convertisseur.mainloop
MainMenu = Tk()
MainMenu.title("Choix de Modes")
button1 = Button(MainMenu, text = "convertisseur", command = ConverterWind)
button1.pack(side = LEFT, padx= 10, pady = 10)
button2 = Button(MainMenu, text = "QUITTER", command = MainMenu.destroy)
button2.pack(side = RIGHT, padx= 10, pady = 10)
MainMenu.mainloop()
You can use the Text.get(Index1,Index2) to get the text from Text widget
Try this.
import tkinter as tk
from tkinter import *
def getText(inputText):
print(inputText.get(1.0,END))
def ConverterWind():
convertisseur = Tk()
convertisseur.title("Convertisseur")
inputZone = Text(convertisseur, height=2, width=50)
inputZone.pack()
getTextArea = Button(convertisseur, text = "Convertir !", command = lambda: getText(inputZone))
getTextArea.pack()
convertisseur.mainloop
MainMenu = Tk()
MainMenu.title("Choix de Modes")
button1 = Button(MainMenu, text = "convertisseur", command = ConverterWind)
button1.pack(side = LEFT, padx= 10, pady = 10)
button2 = Button(MainMenu, text = "QUITTER", command = MainMenu.destroy)
button2.pack(side = RIGHT, padx= 10, pady = 10)
MainMenu.mainloop()
I am a newbie in Python. I want to create a program with Tkinter that takes the entry from the entry "box" and then compares each character of it with the charset and finally pops up a messagebox that shows the phrase. I have almost complete it but I can not make this line work:
info_menu.add_command(label="About",
command=messagebox.showwarning(message="Creator: GakPower\nVersion: 1.0.0\nCreated at 1/5/2017")
Full code:
from tkinter import ttk
from tkinter import *
from tkinter import messagebox
import string as s
class Bruteforcer:
def output(self, result):
self.result = result
if result == "":
messagebox.showwarning(title="Enter a Phrase",
message="Please enter a Phrase!")
else:
messagebox.showinfo(title="Phrase Found!",
message=("The process completed Successfully!\n The Phrase Found!!!!\n", result))
def submit_button_pressed(self):
entry_val = self.entry_value.get()
charset = list(s.ascii_letters + "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρστυφχψω" + s.digits + s.punctuation)
result = ""
x = 0
while x <= len(entry_val)-1:
echar = entry_val[x]
for char in charset:
if char == echar:
result += echar
x += 1
break
return self.output(result)
def __init__(self, root):
self.entry_value = StringVar(root, "")
self.the_menu = Menu(root)
info_menu = Menu(self.the_menu, tearoff=0)
**info_menu.add_command(label="About",
command=messagebox.showwarning(message="Creator: GakPower\nVersion: 1.0.0\nCreated at 1/5/2017")**
)
info_menu.add_separator()
info_menu.add_command(label="Quit", command=root.quit)
self.the_menu.add_cascade(label="Info", menu=info_menu)
root.config(menu=self.the_menu)
text_fond = StringVar()
text_fond.set("Times")
root.title("Graphical Bruteforcer")
root.geometry("500x500")
root.resizable(width=False, height=False)
style = ttk.Style()
style.configure("TButton",
foreground="red",
fond="Times 20",
padding=10)
style.configure("TEntry",
foreground="red",
fond="Times 20",
padding=10)
style.configure("TLabel",
foreground="red",
fond="Times 35 Bold")
# ---------- Entry -----------
self.entry_value = ttk.Entry(root,
textvariable=self.entry_value, width=25, state="normal")
self.entry_value.grid(row=1, columnspan=2)
# ---------- Label ----------
self.secret_label = ttk.Label(root,
text="The Secret Phrase").grid(row=0, column=0)
# ---------- Button ---------
self.button_submit = ttk.Button(root,
text="Submit", command=self.submit_button_pressed)
self.button_submit.grid(row=1, column=2)
root = Tk()
brute = Bruteforcer(root)
root.mainloop()
As furas said in the comments, command= expects a function. So you should replace
info_menu.add_command(label="About",
command=messagebox.showwarning(message="Creator: GakPower\nVersion: 1.0.0\nCreated at 1/5/2017"))
by something like
def show_about():
''' show the about messagebox '''
messagebox.showwarning(message="Creator: GakPower\nVersion: 1.0.0\nCreated at 1/5/2017")
info_menu.add_command(label="About", command=show_about)
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.