Error assigning values to combobox (python 2.7) - 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)**

Related

Issue with the get method of Tkinter (Python 2.x) [duplicate]

This question already has answers here:
Tkinter: AttributeError: NoneType object has no attribute <attribute name>
(4 answers)
Closed 4 years ago.
I am using Tkinter and I am having trouble with the get method. I saw that it was a common issue (here for example 'NoneType' object has no attribute 'get') but I don't really understand how to fix it.
I thought that station_I.get() was suppose to return a string variable but apparently I was wrong.
What is this issue due to ?
PS: I am using Tkinter with Python 2.7
Here is the error I get:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\python\Anaconda2\lib\lib-tk\Tkinter.py", line 1542, in __call__
return self.func(*args)
File "C:/Users/python/Documents/project.py", line 168, in path
print station_I.get()
AttributeError: 'NoneType' object has no attribute 'get'
Here is my code:
from Tkinter import *
import ttk
def path():
print station_I.get()
window = Tk()
stations = ["1","2","3"]
text = StringVar()
text.set("Path: ")
station_I = ttk.Combobox(window, values = stations).place(x=50, y=50)
station_F = ttk.Combobox(window, values = stations).place(x=50, y=100)
bouton = Button(window, command = path, text = "Calculate").place(x=125,y=150)
label = Label(window, textvariable = text).place(x=50,y=225)
window.geometry("330x400")
window.mainloop()
make sure you position your geometry manager on the next line after your variable for your widget
Replace this
station_I = ttk.Combobox(window, values = stations).place(x=50, y=50)
with
station_I = ttk.Combobox(window, values = stations)
station_I.place(x=50, y=50)
and all the variable for the widget variable with the example above.
Full code
from tkinter import *
from tkinter import ttk
def path():
print (station_I.get())
window = Tk()
stations = ["1","2","3"]
text = StringVar()
text.set("Path: ")
station_I = ttk.Combobox(window, values = stations)
station_I.place(x=50, y=50)
station_F = ttk.Combobox(window, values = stations)
station_F.place(x=50, y=100)
bouton = Button(window, command = path, text = "Calculate")
bouton.place(x=125,y=150)
label = Label(window, textvariable = text)
label.place(x=50,y=225)
window.geometry("330x400")
window.mainloop()

Generate tKinter menu with for loop

I have built a simple UI using tKinter, Python 2.7. My code looks like this:
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog, tkMessageBox
class FileZap():
def __init__(self, root):
root.title("Test_App")
root.geometry("900x550")
self.menu = Menu(root)
self.fileMenu = Menu(self.menu)
self.funcMenu = Menu(self.menu)
self.advMenu = Menu(self.menu)
self.toolMenu = Menu(self.menu)
root.config(menu=self.menu, width=500, relief=RAISED, borderwidth=2)
self.menu.add_cascade(label="File", menu=self.fileMenu)
self.menu.add_cascade(label="Functions", menu=self.funcMenu)
self.menu.add_cascade(label="Advanced", menu=self.advMenu)
self.menu.add_cascade(label="Tools", menu=self.toolMenu)
self.menu.add_command(label="Quit", command=root.quit)
self.fileMenu.add_command(label="New")
self.fileMenu.add_command(label="Open")
self.fileMenu.add_command(label="Quit", command=root.quit)
self.funcMenu.add_command(label="Properties")
self.funcMenu.add_command(label="Properties")
self.funcMenu.add_command(label="Properties")
self.funcMenu.add('separator')
self.funcMenu.add_command(label="Properties")
self.funcMenu.add_command(label="Properties")
root = Tkinter.Tk()
file_zap = FileZap(root)
root.mainloop()
I am wondering if I can generate this with better code- specifically using a for loop (or multiple loops).
I tried declaring a list and attempting to iterate through it for some of this, so for example:
menuItems = ['File','Functions','Advanced','Tools','Quit']
for item in menuItems:
self.menu.add_cascade(label=item, menu=self.fileMenu)
to replace this block:
self.menu.add_cascade(label="File", menu=self.fileMenu)
self.menu.add_cascade(label="Functions", menu=self.funcMenu)
self.menu.add_cascade(label="Advanced", menu=self.advMenu)
self.menu.add_cascade(label="Tools", menu=self.toolMenu)
self.menu.add_command(label="Quit", command=root.quit)
but this didn't work out and there is more to consider. I would be grateful if someone could show me a better way of doing this, so I may apply it to the rest of my UI. I have read that using lambda functions might be what I need to do, although again I'm not sure how...
You could use OrderedDict and as you said, run with a loop through the dictionary and add the key which is the label and the menu which is the value.
self.menuItems = OrderedDict([('File',self.fileMenu),('Functions',self.funcMenu),('Advanced',self.advMenu),('Tools', self.toolMenu),('Quit', root.quit)])
for k,v in self.menuItems.items():
self.menu.add_cascade(label=k, menu=v)
Try to understand how those three line works and use their logic.
for k,v in self.menuItems.items():
self.menu.add_cascade(label=k, menu=v)
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog, tkMessageBox
from collections import OrderedDict
class FileZap():
def __init__(self, root):
root.title("Test_App")
root.geometry("900x550")
self.menu = Menu(root)
self.fileMenu = Menu(self.menu)
self.funcMenu = Menu(self.menu)
self.advMenu = Menu(self.menu)
self.toolMenu = Menu(self.menu)
root.config(menu=self.menu, width=500, relief=RAISED, borderwidth=2)
self.menuItems = OrderedDict([('File',self.fileMenu),('Functions',self.funcMenu),('Advanced',self.advMenu),('Tools', self.toolMenu),('Quit', root.quit)])
for k,v in self.menuItems.items():
self.menu.add_cascade(label=k, menu=v)
self.commands = ["New", "Open", "Quit"]
for comm in self.commands:
if comm != "Quit":
self.fileMenu.add_command(label=comm)
else:
self.fileMenu.add_command(label=comm, command=root.quit)
for index in range(6):
if index != 3:
self.funcMenu.add_command(label="Properties")
else:
self.funcMenu.add('separator')
root = Tkinter.Tk()
file_zap = FileZap(root)
root.mainloop()

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

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

Simple Tkinter program is not responding

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