Simple Tkinter program is not responding - python-2.7

So I am following the tutorial Intro to Tkinter and while copying the source code it did not work when I ran the program. I read over my syntax and searched the comments on the video, stack overflow, and I could not find a solution.
import Tkinter
import turtle
import sys
def main():
root = Tkinter.Tk()
cv = Tkinter.Canvas(root, width = 600, height= 600)
cv.pack(side = Tkinter.LEFT)
root.title("Draw")
t = turtle.RawTurtle(cv)
screen = t.getscreen()
screen.setworldcoordinates(0,0,600,600)
frame = Tkinter.Frame(root)
frame.pack(side = Tkinter.RIGHT, fill = Tkinter.BOTH)
def quithandler():
print 'Goodbye'
sys.exit(0)
quitbutton = Tkinter.Button(frame, text='Quit', command = quithandler)
quitbutton.pack()
if __name__ == "__main__":
main()
Also I am running python 2.7 on windows. In this program the quit button does not show up, and the canvas does not respond instantly as I run it. What is causing it to do this every time?
Thank you for any help.

Indent correctly. + You missed root.mainloop() call.
import Tkinter
import turtle
import sys
def main():
root = Tkinter.Tk()
cv = Tkinter.Canvas(root, width = 600, height= 600)
cv.pack(side = Tkinter.LEFT)
root.title("Draw")
t = turtle.RawTurtle(cv)
screen = t.getscreen()
screen.setworldcoordinates(0,0,600,600)
frame = Tkinter.Frame(root)
frame.pack(side = Tkinter.RIGHT, fill = Tkinter.BOTH)
quitbutton = Tkinter.Button(frame, text='Quit', command = quithandler)
quitbutton.pack()
root.mainloop()
def quithandler():
print 'Goodbye'
sys.exit(0)
if __name__ == "__main__":
main()

Related

Error assigning values to combobox (python 2.7)

i am getting an error whenever i try to add values to a combobox (python 2.7). Below is my code.
from Tkinter import *
from tkinter.ttk import *
class StartApp:
def __init__(self,Runtime):
self.Runtime = Runtime
Runtime.title("My App")
self.frame1 = Frame(Runtime, width=500)
self.frame1.grid(sticky='nsew')
self.SearchName_Combobox = Combobox(self.frame1).grid(row=3, column=3, columnspan=10)
self.SearchName_Combobox['values'] = [1,2,3]
root = Tk()
the_app = StartApp(root)
root.mainloop()
i get the following error.
TypeError: 'NoneType' object does not support item assignment
This solves the issue
from Tkinter import *
from tkinter.ttk import *
class StartApp:
def __init__(self,Runtime):
self.Runtime = Runtime
Runtime.title("My App")
self.frame1 = Frame(Runtime, width=500)
self.frame1.grid(sticky='nsew')
**self.SearchName_Combobox = Combobox(self.frame1)**
self.SearchName_Combobox['values'] = [1,2,3]
**self.SearchName_Combobox.grid(row=3, column=3, columnspan=10)**
root = Tk()
the_app = StartApp(root)
root.mainloop()
I tried to explain what i changed but apparently the bold formatting didn't work. This was the change
Original:
self.SearchName_Combobox = Combobox(self.frame1).grid(row=3, column=3, columnspan=10)
Corrected:
self.SearchName_Combobox = Combobox(self.frame1)
self.SearchName_Combobox.grid(row=3, column=3, columnspan=10)**

QThread and pyqtgraph no performance improvement

I am trying to do a multigraph window for plotting different data using pyqtgraph. I have a working version with no threads using timers for getting the data. I also tried a threaded version but it seems to have no performance boost when use htop for visually inspecting the CPU Usage.
I am new to GUIs and Threads so I followed this code that I saw in a youtube tutorial. It uses a QThread to get the CPU usage using psutil.cpu_percent in intervals of 0.1 seconds and then updates a progress bar.
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
import progress
import sysinfo
class MainUIClass(QtGui.QMainWindow, progress.Ui_MainWindow):
def __init__(self, parent = None):
super(MainUIClass, self).__init__(parent)
self.setupUi(self)
self.threadClass = ThreadClass()
self.threadClass.start()
self.connect(self.threadClass, QtCore.SIGNAL('CPU_VALUE'),
self.updateProgressBar)
def updateProgressBar(self, val):
self.progressBar.setValue(val)
class ThreadClass(QtCore.QThread):
def __init__(self, parent = None):
super(ThreadClass, self).__init__(parent)
def run(self):
while 1:
val = sysinfo.getCPU()
self.emit(QtCore.SIGNAL('CPU_VALUE'), val)
if __name__ == '__main__':
a = QtGui.QApplication(sys.argv)
app = MainUIClass()
app.show()
a.exec_()
I tried using cProfile for comparing performance but it throws lot of stuff that couldn't read, so I use the example of the progress bar to average the cpu usage after 10 seconds. Sorry if my measure performance method is so poor.
My two codes for benchmarking are
Threaded Version with a very consistent average CPU Usage of 64%:
import sys
from pyqtgraph.Qt import QtCore
from pyqtgraph.Qt import QtGui
import pyqtgraph as pg
import numpy as np
import time
class GraphWindow_Thread(pg.GraphicsWindow):
def __init__(self, rows, cols, titles):
super(GraphWindow_Thread, self).__init__()
# Code to draw the GUI
self.rows = rows
self.cols = cols
self.titles = titles
self.plots = [] # List of PlotItems
self.curves = [] # List of PlotDataItems in each PlotItem
for i in range(self.rows):
for j in range(self.cols):
p = self.addPlot()
self.plots.append(p)
if titles != [] or len(titles) == 1:
p.setLabel('left', self.titles[i+j+1])
p.setDownsampling(mode='peak')
p.setClipToView(True)
pp = p.plot(pen=(155, 255, 50))
pp1 = p.plot(pen=(55, 130, 255))
self.curves.append((pp, pp1))
self.nextRow()
# Thread to get the data and redraw plots
self.thread_graph = DataThread()
self.thread_graph.start()
self.connect(self.thread_graph, QtCore.SIGNAL('DATA_VALUE'),
self.update_plots)
def set_titles(self, titles):
for i, p in enumerate(self.plots):
p.setLabel('left', titles[i])
def update_plots(self, data, dataD):
for curve in self.curves:
curve[0].setData(data)
curve[1].setData(dataD)
class DataThread(QtCore.QThread):
def __init__(self, parent = None):
super(DataThread, self).__init__(parent)
def run(self):
while 1:
data = np.random.random((30,))
dataD = np.random.random((30,))
self.emit(QtCore.SIGNAL('DATA_VALUE'), data, dataD)
time.sleep(.1)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
gui = GraphWindow_Thread(2,3,[])
gui.show()
app.exec_()
No Thread Version with a very consistent average CPU Usage of 65%:
import sys
from pyqtgraph.Qt import QtCore
from pyqtgraph.Qt import QtGui
import pyqtgraph as pg
import numpy as np
import time
class GraphWindow(pg.GraphicsWindow):
def __init__(self, rows, cols, titles):
super(GraphWindow, self).__init__()
# Code to draw the GUI
self.rows = rows
self.cols = cols
self.titles = titles
self.plots = [] # List of PlotItems
self.curves = [] # List of PlotDataItems in each PlotItem
for i in range(self.rows):
for j in range(self.cols):
p = self.addPlot()
self.plots.append(p)
if titles != [] or len(titles) == 1:
p.setLabel('left', self.titles[i+j+1])
p.setDownsampling(mode='peak')
p.setClipToView(True)
pp = p.plot(pen=(155, 255, 50))
pp1 = p.plot(pen=(55, 130, 255))
self.curves.append((pp, pp1))
self.nextRow()
# Timer to redraw plots
timer = QtCore.QTimer(self)
self.connect(timer, QtCore.SIGNAL('timeout()'),self.update_plots)
timer.start(100)
def set_titles(self, titles):
for i, p in enumerate(self.plots):
p.setLabel('left', titles[i])
def update_plots(self):
np.random.seed()
data = np.random.random((30,))
dataD = np.random.random((30,))
for curve in self.curves:
curve[0].setData(data)
curve[1].setData(dataD)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
gui = GraphWindow(2,3,[])
gui.show()
app.exec_()
The full app is meant to be a window with multiple tabs, each one with a GraphWindow in which each graph uses a Thread for plotting different data.
What am I missing? Why my threaded version does not represent a performance improvement?

Why is the tkinter window blank?

My code uses pygame in order to play all MIDI files within its location, however A Tkinter Slider Window is supposed to show up but it doesn't. And I don't know why.
import os,fnmatch,pygame
import Tkinter as tk
pygame.mixer.init()
root = tk.Tk()
List = []
Song = 0
def getThrottle(event):
Volume = Throttle.get()
print "|"*((Volume)*50/100)
def Update():
List = []
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.mid'):
List.append(file)
return List
class Slider:
def _Init_(self,root):
self.Throttle = self.Scale(master, from_=0, to=100, tickinterval=10, length=200, orient=HORIZONTAL, command=getThrottle)
self.Throttle.set(0)
self.Throttle.pack()
List = Update()
S = Slider()
root.mainloop()
print List
while True:
while Song <= len(List):
pygame.mixer.music.load(List[Song])
pygame.mixer.music.play(1)
while pygame.mixer.music.get_busy() == True:
List=Update()
Song = 3
Song = 0

"AttributeError: class Frame has no attribute 'show_frame'"

this is my code for in which I am trying to link two pages
from Tkinter import *
class Example(Frame):
def __init__( self , parent, controller ):
Frame.__init__(self, parent)
self.controller=controller
self.parent = parent
self.parent.title("f2")
self.parent.configure(background="royalblue4")
self.pack(fill=BOTH, expand=1)
w = 800
h = 500
sw = self.parent.winfo_screenwidth()
sh = self.parent.winfo_screenheight()
x = (sw - w)/2
y = (sh - h)/2
self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
self.logbtn1 = Button(self,text="SIGN UP",font=("Copperplate Gothic Bold",16),bg=("dark green"),activebackground=("green"),command=lambda: controller.show_frame("D:\java prgms\minor\signup"))
self.logbtn1.place(x=325,y=175)
self.logbtn2 = Button(self, text="LOGIN",font=("Copperplate Gothic Bold",16),bg=("cyan"),activebackground=("yellow"),command=lambda: controller.show_frame("D:\java prgms\minor\log1"))
self.logbtn2.place(x=335,y=220)
self.pack()
def main():
root = Tk()
ex = Example(root,Frame)
root.mainloop()
if __name__ == '__main__':
main()
But here I am getting this error message:
AttributeError: class Frame has no attribute 'show_frame'
how to remove this error
First of all, you can not call lambda the way you did in command=lambda: controller.show_frame(...).
Suppose you did the necessary imports that I do not see in your current program, just replace those 2 statements (in 2 lines of your code) by : command=controller.show_frame(...).
Please read about how to use lambda
Second, your code contains an other error around this line:
if name == 'main':
main()
Change it to:
if __name__ == '__main__':
main()
After I fixed your error, I run your program successfully:
P.S. May be you would be interested in this post: What does if __name__ == "__main__": do?

Unexpected Output In Python While Using MoviePy

Hi i added a simple GUI in this script
A python script to automatically summarize soccer videos based on the crowd's reactions
The GUI script is the following
from Tkinter import *
from tkFileDialog import askopenfilename
from soccer_reacts import video_edit
class MyFrame(Frame):
def __init__(self):
master = Tk()
Label(master, text="Please Insert Video Path With Browse", width=30).grid(row=0)
Frame.__init__(self)
self.master.title("Video Editor")
self.master.geometry('{}x{}'.format(300, 200))
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=15)
self.button.grid(row=1, column=0, sticky=W)
self.button2 = Button(self, text="Start", command=self.vid_reactions, width=15)
self.button2.grid(row=2, column=0, sticky=W)
def load_file(self):
fname = askopenfilename(filetypes=(("MP4 files", "*.mp4"),("All files", "*.*") ))
if fname:
self.fname = fname
def vid_reactions(self):
print("[*]Starting operation")
print("[*]File : "+self.fname)
video_edit(self.fname)
print("[*]Operation Finished")
if __name__ == "__main__":
MyFrame().mainloop()
End this is the new code of soccer cuts
import numpy as np # for numerical operations
from moviepy.editor import VideoFileClip, concatenate
def video_edit(file_name):
clip = VideoFileClip(file_name)
cut = lambda i: clip.audio.subclip(i,i+1).to_soundarray(fps=22000)
volume = lambda array: np.sqrt(((1.0*array)**2).mean())
volumes = [volume(cut(i)) for i in range(0,int(clip.audio.duration-2))]
averaged_volumes = np.array([sum(volumes[i:i+10])/10
for i in range(len(volumes)-10)])
increases = np.diff(averaged_volumes)[:-1]>=0
decreases = np.diff(averaged_volumes)[1:]<=0
peaks_times = (increases * decreases).nonzero()[0]
peaks_vols = averaged_volumes[peaks_times]
peaks_times = peaks_times[peaks_vols>np.percentile(peaks_vols,90)]
final_times=[peaks_times[0]]
for t in peaks_times:
if (t - final_times[-1]) < 60:
if averaged_volumes[t] > averaged_volumes[final_times[-1]]:
final_times[-1] = t
else:
final_times.append(t)
final = concatenate([clip.subclip(max(t-5,0),min(t+5, clip.duration))
for t in final_times])
final.to_videofile(file_name) # low quality is the default
When i run the new code, the output is a mp4 file, with the sound of the match
but with no video. I ve checked all the changes i made and i cannot find something wrong. Can anyone help?
I do not why but changing last line from
final.to_videofile(file_name)
to final.write_videofile('The result.mp4')
was a solution