music player playlist - python

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.

Related

could not convert string to float: '' error in python(Tkinter)

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()

Tkinter Text widget returns ".!frame3.!frame3.!frame.!text" instead of appropriate values

I'm currently working on a project where you scan bar codes and it implements the result into an excel file. I am using tkinter to make my GUI, however, when I try to get the values from a text widget it returns the value ".!frame3.!frame3.!frame.!text". how can I fix this to get the appropriate values?
here is my code so far
import tkinter as tk
from tkinter import *
root = tk.Tk(className = "Tool Manager")
root.configure(bg='#C4C4C4')
root.title('Main Screen')
root.geometry("800x600")
main = Frame(root, bg='#C4C4C4', width = 800, height = 600)
#This is the contents of the Main Frame (screen 1)
frame_pad1 = Frame(main, bg='#C4C4C4')
frame_1 = Frame(main,bg='#C4C4C4')
frame_2 = Frame(main, bg='#C4C4C4')
frame_3 = Frame(main, bg='#C4C4C4')
min = Frame(root, bg = 'GREEN')
#mout stuffs
mout = Frame(root, bg = '#C4C4C4')
outframe_pad1 = Frame(mout, bg='#C4C4C4')
outframe_1 = Frame(mout, bg='#C4C4C4')
outframe_2 = Frame(mout, bg='#C4C4C4')
outframe_3 = Frame(mout, bg='#C4C4C4')
#code for changing screens
def raise_frame(frame):
frame.tkraise()
for frame in (main, min, mout):
frame.grid(row=1, column=1, sticky='news')
#sets frame weight for 3 rows (centers frames)
rows = 0
while rows < 3:
root.rowconfigure(rows, weight=1)
root.columnconfigure(rows,weight=1)
rows += 1
def commit_to_file():
ID = name.get()
out_list.get('1.0', 'end-1c')
print(out_list) #<----- THIS IS WHERE I'M RETURNING VALUES TO THE TERMINAL
def on_every_keyboard_input(event):
update_char_length(out_list)
#updating Line Length Information
def update_char_length(out_list):
string_in_text = out_list.get('1.0', '1.0 lineend')
string_length = len(string_in_text)
print(string_length)
if (string_length == 4):
out_list.insert(0.0, '\n')
out_list.mark_set("insert", "%d.%d" % (0,0))
#main screen formatting
area = PhotoImage(file="test.png")
areaLabel = Label(frame_1, image=area, bg='#C4C4C4')
areaLabel.pack(side=RIGHT)
mwLabel = Label(frame_2,text="this is only a test", font=("Airel", 20), bg='#C4C4C4')
mwLabel.pack(side=RIGHT)
out_button = Button(frame_3, text="Check Out", command=lambda:raise_frame(mout) , height=5, width=20, font=("Airel", 15))
out_button.pack(side=RIGHT, padx=20, pady = 4)
in_button = Button(frame_3, text="Check In", command=lambda:raise_frame(min), height=5, width=20, font=("Airel", 15))
in_button.pack(side=LEFT, padx=20, pady = 4)
#out screen formatting
name = Entry(outframe_1, font=("Airel", 15))
name.pack(side=RIGHT)
name_lbl = Label(outframe_1, text="ID Number", bg='#C4C4C4', font=("Airel", 15))
name_lbl.pack(side=LEFT)
outlist = Frame(outframe_2, bd=1, relief=SUNKEN)
outlist.pack(side=LEFT)
out_list = Text(outlist, height=30, width=40)
out_list.pack(side=RIGHT)
done_btn = Button(outframe_3, text="Done", command=commit_to_file, font=("Ariel", 15))
done_btn.pack(side=RIGHT, padx=20, pady=4)
#init to main screen
raise_frame(main)
#drawing objects for main screen
frame_pad1.pack(padx=1, pady=25)
frame_1.pack(padx=1,pady=1)
frame_2.pack(padx=10,pady=1)
frame_3.pack(padx=1, pady=80)
#drawing out screen
outframe_1.pack(padx=1, pady=1)
outframe_2.pack(padx=1,pady=1)
outframe_3.pack(padx=1, pady=1)
#calls line info update out screen
out_list.bind('<KeyRelease>', on_every_keyboard_input)
root.mainloop()
You are printing the command and not the value of it. Put the command in a variable and then print the variable.
Example: myVar = out_list.get("1.0", "end-1c") and then print(myVar)

Making a new window with an input widget using tkinter

I can't seem to make my new window display the inputer code
it only displays a new empty window without the labels and the input widget
i want to make a simple GUI for a school project, but i dont want to type the name in the python shell, but in the interface
please help and tell me where im wrong, im still new to python
from collections import deque
first = deque([])
last = deque([])
nom = 0
import tkinter as tk
from tkinter import *
class Application(tk.Frame):
def __init__(self, master=None, nom=0, priono=1, prio=1):
super().__init__(master)
self.pack()
self.create_widgets()
self.nom= nom
self.priono= priono
self.prio=prio
def create_widgets(self):
self.add = tk.Button(self, bg ="black", fg="pink")
self.add["text"] = "-----Add to queue-----\n(click me)"
self.add["command"] = self.create_window
self.add.pack(side="top", pady = 10, padx = 20)
self.add["font"] = "Times 16 bold"
self.remov = tk.Button(self, bg ="black", fg="pink")
self.remov["text"]= "---Remove in queue---\n(click me)"
self.remov["command"] = self.remov_
self.remov.pack(side="top", pady = 10, padx = 20)
self.remov["font"] = "Times 16 bold"
self.quit = tk.Button(self, text="QUIT", fg="white", bg = "red",
command=root.destroy)
self.quit.pack(side="bottom")
def create_window(self):
def inputer(self):
self.L1 = tk.Label(self, text = "Name")
self.L1.pack( side = LEFT)
self.E1 = tk.Entry(self, bd =5)
self.E1.pack(side = RIGHT)
win2 = Toplevel(self)
win2.button = Button(self, text='Ready?\nClick Here', command=inputer)
def say_hi(self):
print("hi there, everyone!")
def add_1(self):
name=input("What is your name? ")
first.append(name)
print("Good Day!",first[self.nom])
print("Your priority number is:","%03d" % (self.priono))
self.priono+=1
self.nom+= 1
def remov_(self):
if (len(first)) >= 1:
first.popleft()
else:
print("No one left in queue")
root = tk.Tk()
root.config(background="black")
app = Application(master=root)
app.master.title("ID QUEUEING SYSTEM beta")
app.master.minsize(540, 360)
app.master.maxsize(600, 500)
app.mainloop()
You must use your toplevel to indicate where the widgets must appear; you must also pack (place or grid) the widgets belonging to your toplevel window.
The code from inputer needed to be placed outside of the inner function; you can now write the code to have this inputer do what you need it to do:
I removed the star import and added the prefix tk. to all tkinter method calls.
import tkinter as tk
from collections import deque
class Application(tk.Frame):
def __init__(self, master=None, nom=0, priono=1, prio=1):
super().__init__(master)
self.pack()
self.create_widgets()
self.nom = nom
self.priono= priono
self.prio=prio
def create_widgets(self):
self.add = tk.Button(self, bg ="black", fg="pink")
self.add["text"] = "-----Add to queue-----\n(click me)"
self.add["command"] = self.create_window
self.add.pack(side="top", pady = 10, padx = 20)
self.add["font"] = "Times 16 bold"
self.remov = tk.Button(self, bg ="black", fg="pink")
self.remov["text"]= "---Remove in queue---\n(click me)"
self.remov["command"] = self.remov_
self.remov.pack(side="top", pady = 10, padx = 20)
self.remov["font"] = "Times 16 bold"
self.quit = tk.Button(self, text="QUIT", fg="white", bg = "red",
command=root.destroy)
self.quit.pack(side="bottom")
def create_window(self):
def inputer():
print('inputer ', end=': ')
print(self.E1.get())
win2 = tk.Toplevel(self)
win2_button = tk.Button(win2, text='Ready?\nClick Here', command=inputer)
win2_button.pack()
self.L1 = tk.Label(win2, text = "Name")
self.L1.pack( side=tk.LEFT)
self.E1 = tk.Entry(win2, bd =5)
self.E1.pack(side=tk.RIGHT)
def say_hi(self):
print("hi there, everyone!")
def add_1(self):
name=input("What is your name? ")
first.append(name)
print("Good Day!",first[self.nom])
print("Your priority number is:","%03d" % (self.priono))
self.priono+=1
self.nom+= 1
def remov_(self):
if (len(first)) >= 1:
first.popleft()
else:
print("No one left in queue")
root = tk.Tk()
root.config(background="black")
app = Application(master=root)
app.master.title("ID QUEUEING SYSTEM beta")
app.master.minsize(540, 360)
app.master.maxsize(600, 500)
app.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()

update tkinter label from serial data whenever there's new data from serial port python 3.x

I have encounter this problem where i could not display any value on the label which i wanted to constantly update it whenever there's new data coming in from the serial port. I'm new to python, really need the help.
import tkinter
import tkinter.messagebox
import serial
import time
ser = serial.Serial(
port='COM5',\
baudrate=9600,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=4)
class Menu:
def __init__(self):
self.main_window = tkinter.Tk()
self.main_window.title("Room Light System")
self.main_window.geometry("1200x600")
#Frames
self.frame_2 = tkinter.Frame(self.main_window, bg='Orange') # Receiving DATAs
#ReceiveLabel
self.ReceiveLabel = tkinter.Label(self.frame_2,\
text = 'Received DATAs',\
bg = 'White',\
height = 2, width = 20)
#Temperature
self.GetTempLabel = tkinter.Label(self.frame_2,\
text='Temperature :')
self.TempValue = tkinter.StringVar()
self.GetTempValueLabel = tkinter.Label(self.frame_2,bg = 'Green',\
textvariable = self.TempValue
)
#PACKING!!! F2
self.frame_2.pack()
self.frame_2.place(x=410, y=0, height=300, width=400)
#ReceiveLabel
self.ReceiveLabel.pack()
self.ReceiveLabel.place(x=100, y=10)
#Temperature
self.GetTempLabel.pack()
self.GetTempLabel.place(x=50, y=80, height=20, width=120)
self.GetTempValueLabel.pack()
self.GetTempValueLabel.place(x=200, y=80, height=20, width=50)
#main loop and quit
self.quitButton = tkinter.Button(self.main_window,\
text = 'Quit',
command = self.main_window.destroy,\
height = 2, width = 6)
self.quitButton.pack()
self.quitButton.place(x=200, y=500)
tkinter.mainloop()
def GetTemp(self):
data = bytearray()
while(1):
readline = ser.read(size=10)
if len(readline) > 0 :
data = readline
v = memoryview(data)
P = v.tobytes()
P = P.decode(encoding='UTF-8')
self.TempValue.set(P)
gui = Menu()
ser.close()
You can run your GetTemp() method in a seperated thread from _thread module. The thread is called with the Tkinter method after(). In following example I substituted your GetTemp() with a randomn number generated.
import tkinter
import tkinter.messagebox
import time
import random
import _thread
class Menu:
def __init__(self):
self.main_window = tkinter.Tk()
self.main_window.title("Room Light System")
self.main_window.geometry("1200x600")
#Frames
self.frame_2 = tkinter.Frame(self.main_window, bg='Orange') # Receiving DATAs
#ReceiveLabel
self.ReceiveLabel = tkinter.Label(self.frame_2,\
text = 'Received DATAs',\
bg = 'White',\
height = 2, width = 20)
#Temperature
self.GetTempLabel = tkinter.Label(self.frame_2,\
text='Temperature :')
self.TempValue = tkinter.StringVar()
self.GetTempValueLabel = tkinter.Label(self.frame_2,bg = 'Green',\
textvariable = self.TempValue
)
#PACKING!!! F2
self.frame_2.pack()
self.frame_2.place(x=410, y=0, height=300, width=400)
#ReceiveLabel
self.ReceiveLabel.pack()
self.ReceiveLabel.place(x=100, y=10)
#Temperature
self.GetTempLabel.pack()
self.GetTempLabel.place(x=50, y=80, height=20, width=120)
self.GetTempValueLabel.pack()
self.GetTempValueLabel.place(x=200, y=80, height=20, width=50)
#main loop and quit
self.quitButton = tkinter.Button(self.main_window,\
text = 'Quit',
command = self.main_window.destroy,\
height = 2, width = 6)
self.quitButton.pack()
self.quitButton.place(x=200, y=500)
self.main_window.after(2000, _thread.start_new_thread, self.GetTemp, ())
tkinter.mainloop()
def GetTemp(self):
while(1):
value = random.random()
self.TempValue.set(str(value))
time.sleep(0.5)
gui = Menu()
call serial inside the method..it will work..here is my code for serial using Mr Holger's concept..
this code is tested with Raspberry Pi3 serial port ttyS0 as master and serially connected sensor.....
import tkinter
import tkinter.messagebox
import time
import _thread
import serial
class Menu:
def __init__(self):
self.main_window = tkinter.Tk()
self.main_window.title("Serial Data monitor")
self.main_window.geometry("1000x600")
#Frames
self.frame_2 = tkinter.Frame(self.main_window, bg='Orange') # Receiving DATAs
#ReceiveLabel
self.ReceiveLabel = tkinter.Label(self.frame_2,\
text = 'Received DATAs',\
bg = 'White',\
height = 2, width = 20)
#RPM
self.GetTempLabel = tkinter.Label(self.frame_2,\
text='RPM :')
self.TempValue = tkinter.StringVar()
self.GetTempValueLabel = tkinter.Label(self.frame_2,bg = 'Green',\
textvariable = self.TempValue
)
#torque
self.GetTemppLabel = tkinter.Label(self.frame_2,\
text='TORQUE :')
self.TemppValue = tkinter.StringVar()
self.GetTemppValueLabel = tkinter.Label(self.frame_2,bg = 'Green',\textvariable = self.TempValue)
PACKING!!! F2
self.frame_2.pack()
self.frame_2.place(x=410, y=0, height=300, width=400)
#ReceiveLabel
self.ReceiveLabel.pack()
self.ReceiveLabel.place(x=100, y=10)
#rpm
self.GetTempLabel.pack()
self.GetTempLabel.place(x=50, y=80, height=20, width=80)
self.GetTempValueLabel.pack()
self.GetTempValueLabel.place(x=200, y=80, height=20, width=120)
#torque
self.GetTemppLabel.pack()
self.GetTemppLabel.place(x=50, y=120, height=20, width=80)
self.GetTemppValueLabel.pack()
self.GetTemppValueLabel.place(x=200, y=120, height=20, width=120)
#main loop and quit
self.quitButton = tkinter.Button(self.main_window,\
text = 'Quit',
command = self.main_window.destroy,\
height = 2, width = 6)
self.quitButton.pack()
self.quitButton.place(x=200, y=500)
self.main_window.after(2000, _thread.start_new_thread, self.GetTemp, ())
self.main_window.after(4000, _thread.start_new_thread, self.GetTempp, ())
tkinter.mainloop()
def GetTemp(self):
s=serial.Serial(port='/dev/ttyS0',baudrate=9600)
string='*00T%'
while True:
s.write(str.encode(string))
print(string)
time.sleep(2)
if s.inWaiting():
temp=s.readline(s.inWaiting())
value=temp.decode('utf-8')
value=value[5:-1]
def GetTempp(self):
s=serial.Serial(port='/dev/ttyS0',baudrate=9600)
string1='*01T%'
while True:
s.write(str.encode(string1))
print(string1)
time.sleep(2)
if s.inWaiting():
tempp=s.readline(s.inWaiting())
value1=tempp.decode('utf-8')
value1=value1[5:-1]
print(value1)
self.TemppValue.set(str(value1))
time.sleep(0.5)
gui = Menu()

Categories

Resources