Python can't assign function to call - python

i am doing a project in python in tkinter, to find out you age. in one line it says can't assign function to call. here is the line:
int(y_born_in) = Entry(window, width=20, bg="yellow", foreground = "purple", font = "X-Files")
( i got bored so i added fonts & stuff)
here is my actual code if you need it:
from tkinter import *
#key press function:
def click():
output.delete(0.0, END)
output.insert (2014 - int(y_born_in))
output.insert ("\n or it could be")
output.insert ( 2015 - int(y_born_in))
#code for the enter button
def enter_click(Event):
output.delete(0.0, END)
output.insert (2014 - int(y_born_in))
output.insert ("\n or it could be")
output.insert ( 2015 - int(y_born_in))
#collect text from text entry box
window = Tk()
window.title("how old are you?")
window.configure(background = "cyan")
#create label:
Label(window, text="please insert the year you were born", background = "hot pink",foreground = "light green", font = "X-Files") .grid( sticky=N)
#create text entry box
int(y_born_in) = Entry(window, width=20, bg="yellow", foreground = "purple", font = "X-Files")
y_born_in.grid(row=1, column=0,sticky=N)
#add a submit button
submit = Button(window, text="SUBMIT", width=6, command=click, background = "purple", fg = "yellow", font = "X-Files") .grid( sticky=N)
#create another label
Label(window, text="you were born in the year", background = "blue", foreground = "red", font = "X-Files") .grid( sticky=N)
#create text box
output = Text(window, width=75, height=8, wrap=WORD, background="coral", fg = "blue", font = "X-Files")
output.grid( sticky=N)
#enter key works as the button
window.bind("<Return>", enter_click )
window.mainloop()

You can't call int on the left side of an assignment statement. Instead, just do:
y_born_in = Entry(window, width=20, bg="yellow", foreground = "purple", font = "X-Files")
If you're trying to tell the program, "y_born_in should be an Entry that only accepts digits for input", that's a bit trickier. See Interactively validating Entry widget content in tkinter or Adding validation to an Entry widget for details.
Additionally, everywhere that you're trying to do int(y_born_in) to get what the user typed (like in click or enter_click), you should instead be doing int(y_born_in.get()).

Related

How to set font size and font of my text within a function in TkInter?

I'm not sure what is wrong with me but I can't seem to figure out how to set the font size of my text within my "instructions" function.
import random
import time
num = random.randint(1, 100)
root = Tk()
root.title("Mack's totally advanced Number Guesser!")
root.geometry('404x300')
##root.resizable(False,False)
root.configure(bg='black')
fontA = 'BigNoodleTitling'
fontSizeA = 20
def instructions():
text = StringVar()
welcomeLbl.grid_forget()
instrButton.grid_forget()
startButton.grid_forget()
insL = Label(root, textvariable=text, fg='pink', bg='black').grid(row=2, pady=100)
text.set('So you need instructions eh?')
titleLbl = Label(root)
titleLbl['borderwidth'] = (2)
titleLbl['relief'] = ('solid')
titleLbl['text'] = ("Mack's totally advanced Number Guessing Game!")
titleLbl['font'] = (fontA, fontSizeA)
titleLbl.grid(row=0, column=0)
welcomeLbl = Label(root, fg='white', bg='black')
welcomeLbl['text'] = ("Welcome Random Person")
welcomeLbl['font'] = (fontA, 30)
welcomeLbl.grid(row=2, column=0, pady=20)
instrButton = Button(root, command=instructions)
instrButton['text'] = ("Instructions")
instrButton['font'] = (fontA, fontSizeA)
instrButton.grid(row=3,column=0, sticky=N)
startButton = Button(root, fg='red')
startButton['text'] = ("Start")
startButton['font'] = (fontA, 40)
startButton.grid(row=4,column=0, columnspan=1, sticky=E+W, pady=25)
Can anyone help me with setting the font and font size of my "So you need instructions Eh?"
Thanks.
When creating a label or button, or anything really with text in it, you can define the font and font size as follows
from tkinter import *
root = Tk()
label1 = Label(root, text = 'Hello' font = ('Calibri', 12))
When the first parameter for the 'font' function is the font name (as long as you have the font installed to your computer it should work) and the second parameter is the font size.

tkinter past text keeping font

I have a tkinter text widget and I would be able to copy a text from excel (as exemple) and past it into my text widget 'tC' and keep the font define in excel, like bold, italics, color ect.. for now i just get the text black and basic. I don't get if it's just the display or the font is not past. Thanks you
Here is how I create my text label:
windPop = tk.Toplevel()
windPop.attributes('-topmost', 'true')
windPop.wm_geometry("600x600")
frm1 = tk.LabelFrame(windPop)
frm1.pack(side=tk.TOP)
labT = tk.Label(frm1, text="Titre", bg="white", height=1, width=10)
labT.grid(row=0,column=1)
tT = tk.Text(frm1, height=1, width=10, bg="white")
tT.grid(row=0,column=2)
frm3 = tk.LabelFrame(windPop)
frm3.pack()
labT = tk.Label(frm3, text="Genre", bg="white", height=1, width=10)
labT.grid(row=0,column=1)
sexMail = tk.StringVar(frm3)
sexMail.set("neutre")
tG = tk.OptionMenu(frm3, windows.genreMailVariable, *windows.genreMail)
tG.grid(row=0,column=2)
frm2 = tk.LabelFrame(windPop)
frm2.pack()
labC = tk.Label(frm2, text="Corps du mail", bg="white", width=20)
labC.grid(row=0,column=1)
tC = tk.Text(frm2, height=30, width=40, bg="white")
tC.grid(row=0,column=2)
bb = tk.Button(windPop, text='valider creation', width=20)
bb.pack(pady=10, side=tk.BOTTOM)
bb.configure(command=lambda w=windows, corp=tC, titre=tT, genre=sexMail, par=windPop :self.valid_creation(w, corp, titre, genre, par))
There is no support for this in tkinter. Tkinter can't get font information from the clipboard.

Tkinter - How to display image when clicking a button?

First time here so forgive me as this is my FIRST attempt at making a silly GUI game (if you want to call it that). I'm trying to get the user to click a button and the image of their selection pops up. I can't seem to figure out how to get the image to pop up though.
Image does show if I run it separately.
My code:
from Tkinter import *
root = Tk()
class PokemonClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text="Welcome! Pick your Pokemon!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.CharButton = Button(root, text="Charmander", bg="RED", fg="White",
command=self.CharClick)
self.CharButton.pack(side=LEFT, fill=X)
self.SquirtButton = Button(root, text="Squirtle", bg="Blue", fg="White")
self.SquirtButton.pack(side=LEFT, fill=X)
self.BulbButton = Button(root, text="Bulbasaur", bg="Dark Green",
fg="White")
self.BulbButton.pack(side=LEFT, fill=X)
def CharClick(self):
print "You like Charmander!"
global CharSwitch
CharSwitch = 'Yes'
CharSwitch = 'No'
if CharSwitch == 'Yes':
CharPhoto = PhotoImage(file="Charmander.gif")
ChLabel = Label(root, image=CharPhoto)
ChLabel.pack()
k = PokemonClass(root)
root.mainloop()
This works, but the actual image no longer shows, if I keep the PhotoImage OUT of the class it will print but I want to have it print IF they click the specific button:
from Tkinter import *
root = Tk()
class PokemonClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text = "Welcome! Pick your Pokemon!", bg = "Black", fg = "White")
self.WelcomeLabel.pack(fill = X)
self.CharButton = Button(root, text = "Charmander", bg = "RED", fg = "White", command = CharClick)
self.CharButton.pack(side = LEFT, fill = X)
self.SquirtButton = Button(root, text = "Squirtle", bg = "Blue", fg = "White")
self.SquirtButton.pack(side = LEFT, fill = X)
self.BulbButton = Button(root, text = "Bulbasaur", bg = "Dark Green", fg = "White")
self.BulbButton.pack(side = LEFT, fill = X)
def CharClick():
print "You like Charmander!"
CharPhoto = PhotoImage(file = "Charmander.gif")
ChLabel = Label(root, image = CharPhoto)
ChLabel.pack()
k = PokemonClass(root)
root.mainloop()
You need to maintain a reference to your PhotoImage object. Unfortunately there is an inconsistency in tkinter in that attaching a Button to a parent widget increments the reference count, but adding an image to a widget does not increment the reference count. As a consequence at the moment the CharPhoto variable goes out of scope at the end of the function CharClick, the number of reference to the PhotoImage falls to zero and the object is made available for garbage collection.
If you keep a reference to the image somewhere, it will appear. When you kept it globally it remained in scope for the entire script and hence appeared.
You can keep a reference to it in the PokemonClass object or in the Label widget.
Below is the later of those options
from Tkinter import *
root = Tk()
class PokemonClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text="Welcome! Pick your Pokemon!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.CharButton = Button(root, text="Charmander", bg="RED", fg="White",
command=self.CharClick)
self.CharButton.pack(side=LEFT, fill=X)
self.SquirtButton = Button(root, text="Squirtle", bg="Blue", fg="White")
self.SquirtButton.pack(side=LEFT, fill=X)
self.BulbButton = Button(root, text="Bulbasaur", bg="Dark Green",
fg="White")
self.BulbButton.pack(side=LEFT, fill=X)
def CharClick(self):
print "You like Charmander!"
global CharSwitch
CharSwitch = 'Yes'
CharPhoto = PhotoImage(file="Charmander.gif")
ChLabel = Label(root, image=CharPhoto)
ChLabel.img = CharPhoto
ChLabel.pack()
CharSwitch = 'No'
k = PokemonClass(root)
root.mainloop()
The solution which helped me is just simply declaring all the image variables on the next line after 'root = Tk()'. Doing so won't spoil your code or anything.

Highlight text when clicked in tkinter

I'm working on my Python program (on an Ubuntu system), and I have little idea of what I am doing: I am importing media filenames from a folder, and print it in a Text widget, and then click it to open on VLC Player.
I just want to add an additional feature, that is: when I click on any filename, it should be highlight and then open on VLC.
Can you please guide me on how can I do it?
import subprocess,os
from Tkinter import *
def viewFile():
tex.delete('1.0', END)
for f in os.listdir(path):
if f.endswith('.h264'):
linkname="link-" + f
tex.insert(END,f + "\n", linkname)
tex.tag_configure(linkname, foreground="blue", underline=True)
tex.tag_bind(linkname, "<1>", lambda event, filename =path+'/'+f: subprocess.call(['vlc',filename])) # Video play on VLC Player
if __name__ == '__main__':
root = Tk()
step= root.attributes('-fullscreen', True)
step = LabelFrame(root,text="FILE MANAGER", font = "Arial 20 bold italic")
step.grid(row=1, columnspan=7, sticky='W',padx=100, pady=5, ipadx=130, ipady=25)
Button(step, text="ViewFile", font = "Arial 8 bold italic", activebackground="turquoise", width=30, height=5, command=viewFile).grid (row= 6, column =3)
Button(step, text="Exit", font = "Arial 8 bold italic", activebackground="turquoise", width=20, height=5, command=root.quit).grid (row= 6, column =5)
tex = Text(master=root) # TextBox For Displaying File Information
scr=Scrollbar(root,orient =VERTICAL,command=tex.yview)
scr.grid(row=8, column=2, rowspan=15, columnspan=1, sticky=NS)
tex.grid(row=8, column=1, sticky=E)
tex.config(yscrollcommand=scr.set,font=('Arial', 8, 'bold', 'italic'))
global process
path = os.path.expanduser("~/python") # Define path To play, delete, or rename video
root.mainloop()
I modified your example to have the lines highlight. How to highlight a line is explained here. Basicly I added a text_click_callback that check which line is clicked and highlight it and calls vlc. I changed the input folder, to be able to execute the code, as I dont have any video files to work with.
import subprocess,os
from Tkinter import *
def text_click_callback(event):
# an event to highlight a line when single click is done
line_no = event.widget.index("#%s,%s linestart" % (event.x, event.y))
#print(line_no)
line_end = event.widget.index("%s lineend" % line_no)
event.widget.tag_remove("highlight", 1.0, "end")
event.widget.tag_add("highlight", line_no, line_end)
event.widget.tag_configure("highlight", background="yellow")
def viewFile():
tex.delete('1.0', END)
for f in os.listdir(path):
#if f.endswith('.h264'):
linkname="link-" + f
tex.insert(END,f + "\n", linkname)
tex.tag_configure(linkname, foreground="blue", underline=True)
tex.tag_bind(linkname, "<Button-1>", text_click_callback ) # highlight a line
tex.tag_bind(linkname, "<Double-Button-1>", lambda event, filename =path+'/'+f: subprocess.call(['vlc',filename]) ) # Video play on VLC Player
if __name__ == '__main__':
root = Tk()
#step= root.attributes('-fullscreen', True)
step = LabelFrame(root,text="FILE MANAGER", font = "Arial 20 bold italic")
step.grid(row=1, columnspan=7, sticky='W',padx=100, pady=5, ipadx=130, ipady=25)
Button(step, text="ViewFile", font = "Arial 8 bold italic", activebackground="turquoise", width=30, height=5, command=viewFile).grid (row= 6, column =3)
Button(step, text="Exit", font = "Arial 8 bold italic", activebackground="turquoise", width=20, height=5, command=root.quit).grid (row= 6, column =5)
tex = Text(master=root) # TextBox For Displaying File Information
scr=Scrollbar(root,orient =VERTICAL,command=tex.yview)
scr.grid(row=8, column=2, rowspan=15, columnspan=1, sticky=NS)
tex.grid(row=8, column=1, sticky=E)
tex.config(yscrollcommand=scr.set,font=('Arial', 8, 'bold', 'italic'))
global process
path = os.path.expanduser("/tmp") # Define path To play, delete, or rename video
root.mainloop()
How it works is shown below:
But I think Bryan Oakley is right. A listbox would be better for this. Nevertheless, if you want to keep using Text, you can do as in the example provided.

Using Entry box with Tkinter in Grid manager?

I'm trying to make a basic GUI using Tkinter and have an entry box next to my label using a Grid manager, but the window is not showing when I run my program if I use .grid() with my Entry object.
It does work when I use .pack(), which is strange because I heard not to use .pack() when I have other things using .grid() in the same widget. But I do want to use .grid() because I want to be able to organize it how I want to.
Code is below, I'm having trouble with Entry object showName. The commented out .pack() statement is the one that does work, the .grid() statement is the one that does not work.
Does anybody know what's wrong with this?
from Tkinter import *
class RenamerGUI():
def __init__(self, master):
frame = Frame(master)
frame.pack() #Make frame visible
self.exit = Button(frame, text = "Exit", fg = "red", command = frame.quit)
self.csv2tsv = Button(frame, text = "csv2tsv", fg = "green", bg = "black", command=self.csv2tsv)
self.epguidestsvFormatter = Button(frame, text = "epguidestsvFormatter", fg = "green", bg = "black", command = self.epguidestsvFormatter)
self.epNamesList = Button(frame, text = "epNamesList", fg = "green", bg = "black", command = self.epNamesList)
self.SeasonSplitter = Button(frame, text = "SeasonSplitter", fg = "green", bg = "black", command = self.SeasonSplitter)
self.Renamer = Button(frame, text = "Renamer", fg = "green", bg = "black", command = self.Renamer)
self.showLabel = Label(frame, text = "Show: ")
self.showName = Entry(master)
self.get = Button(frame, text = "Get", command = self.textgetter)
self.exit.grid(row=3, column=4)
self.csv2tsv.grid(row=1, column = 0)
self.epguidestsvFormatter.grid(row=1, column=1)
self.epNamesList.grid(row=1, column=2)
self.SeasonSplitter.grid(row=1, column=3)
self.Renamer.grid(row=1, column=4)
self.showLabel.grid(row=2)
self.showName.grid(row=2, column=1)
#self.showName.pack(side=BOTTOM)
The entry has the wrong parent:
self.showName = Entry(master)
should be
self.showName = Entry(frame)

Categories

Resources