When I run this code:
from Tkinter import *
import tkFont
class Statify():
def __init__(self):
### Broken
self.titleFont = tkFont.Font(family='Helvetica', size=24, weight='bold')
self.option_add(*Label*font, self.titleFont)
###
self.root = Tk()
self.root.withdraw()
self.main = Toplevel(self.root)
self.main.title('')
self.main_header = Frame(self.main)
self.main_footer = Frame(self.main)
self.main_title = Label(self.main_header, text='Statify Me v1.0 (WIP)')
self.main_exit = Button(self.main_footer, text='Quit', command=quit)
self.main_header.pack()
self.main_footer.pack()
self.main_title.pack()
self.main_exit.pack()
mainloop()
statify = Statify()
I get:
Traceback (most recent call last):
File "Statify.py", line 23, in <module>
statify = Statify()
File "Statify.py", line 7, in __init__
self.titleFont = tkFont.Font(family='Helvetica', size=24, weight='bold')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/tkFont.py", line 88, in __init__
AttributeError: 'NoneType' object has no attribute 'tk'
From what I've read, this should work, and using an option file instead doesn't make a difference.
Python version 2.7.2
Tkinter verion 8.5
If you look at the docs for tkFont, you'll see that the problem is that tkFont.Font requires a root argument - i.e. a parent widget. Fix this by moving the call to tkFont.Font below where you create the root window, then add self.root as a keyword argument, like so:
self.root = Tk()
self.titleFont = tkFont.Font(root=self.root, family='Helvetica', size=24, weight='bold')
^^^^^^^^^^^^^^
You haven't gotten to this bug yet, but there are problems with the next line - I think you meant to write self.root.option_add rather than self.option_add, and I don't know what you're trying to do with the *Label*font business.
Related
I decided to make a tkinter timer but am receiving a very strange error.
Here is the code and the error:
import tkinter as tk
import time
window = tk.Tk()
window.title("Hello wold")
window.geometry("300x300")
timer = int(input("time in seconds"))
for i in range(timer):
timer -= 1
print(timer)
time.sleep(1)
hello = tk.Label("timer")
hello.pack()
tk.mainloop()
The error:
Traceback (most recent call last):
File "main.py", line 14, in <module>
hello = tk.Label("timer")
File "/usr/lib/python3.8/tkinter/__init__.py", line 3143, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "/usr/lib/python3.8/tkinter/__init__.py", line 2561, in __init__
BaseWidget._setup(self, master, cnf)
File "/usr/lib/python3.8/tkinter/__init__.py", line 2530, in _setup
self.tk = master.tk
AttributeError: 'str' object has no attribute 'tk'
To change the text of a label you need to define the text property:
hello = tk.Label(text="timer")
This will set the text of the label to "timer", but if you want to set it as the variable you previously declared (called timer) - simply remove the quotation marks.
hello = tk.Label(text=timer)
This will set the text of the label to whatever the variable 'timer' is equal to.
However you also need to set the window, which leaves the final code to this:
hello = tk.Label(window, text=timer)
I added tk.StringVar in line 16.
I added textvariable=string_variable in line 17
tk.mainloop was relocated outside of the loop block in line 20
Here is code:
import tkinter as tk
import time
window = tk.Tk()
window.title("Hello wold")
window.geometry("300x300")
timer = int(input("time in seconds"))
for i in range(timer):
timer -= 1
print(timer)
time.sleep(1)
string_variable = tk.StringVar(window, timer)
hello = tk.Label(window, textvariable=string_variable)
hello.pack()
tk.mainloop()
Output result:
I have a very basic question, i.e. by using Python Tkinter window I want to show list box and from that list, I want to show some information which I select. But I am getting some error.
import Tkinter
from Tkinter import*
import tkMessageBox
window = Tk()
window.title('ex - 4,listing option')
frame = Frame(window)
listbox = Listbox(frame)
listbox.insert(1, 'Manual')
listbox.insert(2, 'Auto')
listbox.insert(3, 'AI')
def dialog():
tkMessageBox('selection','your chice:' + \
listbox.get(listbox.curselection()))
btn = Button(frame, text = 'Choose',command = dialog)
btn.pack(side = RIGHT, padx = 5)
listbox.pack(side = LEFT)
frame.pack(padx = 30, pady = 30)
window.mainloop()
The error is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Users\Subhro Jyoti\Desktop\python\ex - 4,listing option", line 12, in dialog
tkMessageBox('selection','your chice:' + listbox.get(listbox.curselection()))
TypeError: 'module' object is not callable
tkMessageBox is a collection of different types of message boxes, you have to indicate which one you want to use. For example:
def dialog():
tkMessageBox.showinfo('selection','your chice:' +
listbox.get(listbox.curselection()))
Your choices are showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, or askretrycancel
I'm trying to insert a gif image in a new tkinter window when a button is clicked but I keep getting this error
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\idlelib\run.py", line 119, in main
seq, request = rpc.request_queue.get(block=True, timeout=0.05)
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\queue.py", line 172, in get
raise Empty
queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:/Users/Afro/Desktop/mff.py", line 8, in sex
canvas = tkinter.Label(wind,image = photo)
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 2605, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 2138, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage1" doesn't exist
Here's the code. The image and the location actually exists.
import tkinter
def six():
wind = tkinter.Tk()
photo = tkinter.PhotoImage(file = 'American-Crime-Story-1.gif')
self = photo
canvas = tkinter.Label(wind,image = photo)
canvas.grid(row = 0, column = 0)
def base():
ssw = tkinter.Tk()
la = tkinter.Button(ssw,text = 'yes',command=six)
la.grid()
base()
What am I doing wrong?
You are trying to create two instances of Tk window. You can't do that. If you want second window or pop-up window you should use Toplevel() widget.
Also, self doesn't mean anything in this context. Using the widget's image property would be better to keep a reference.
import tkinter
ssw = tkinter.Tk()
def six():
toplvl = tkinter.Toplevel() #created Toplevel widger
photo = tkinter.PhotoImage(file = 'American-Crime-Story-1.gif')
lbl = tkinter.Label(toplvl ,image = photo)
lbl.image = photo #keeping a reference in this line
lbl.grid(row=0, column=0)
def base():
la = tkinter.Button(ssw,text = 'yes',command=six)
la.grid(row=0, column=0) #specifying row and column values is much better
base()
ssw.mainloop()
I'm trying to add a ttk calendar into my Tkinter GUI. The problem is that it raises _tkinter.TclError: can't pack .34164128 inside .34161248.34161448.34161608
import Tkinter
import tkSimpleDialog
import ttkcalendar
class CalendarDialog(tkSimpleDialog.Dialog):
"""Dialog box that displays a calendar and returns the selected date"""
def body(self, master):
self.calendar = ttkcalendar.Calendar(master)
self.calendar.pack()
def apply(self):
self.result = self.calendar.selection
# Demo code:
def main():
root = Tkinter.Tk()
root.wm_title("CalendarDialog Demo")
def onclick():
print 'click'
cd = CalendarDialog(root)
button = Tkinter.Button(root, text="Click me to see a calendar!", command=onclick)
button.pack()
root.update()
root.mainloop()
if __name__ == "__main__":
main()
TRACEBACK:
File "C:/Users/Milano/PycharmProjects/MC/plots/ds.py", line 32, in <module>
main()
File "C:/Users/Milano/PycharmProjects/MC/plots/ds.py", line 23, in main
cd = CalendarDialog(root)
File "C:\Python27\lib\lib-tk\tkSimpleDialog.py", line 64, in __init__
self.initial_focus = self.body(body)
File "C:/Users/Milano/PycharmProjects/MC/plots/ds.py", line 9, in body
self.calendar = ttkcalendar.Calendar(master)
File "C:\Users\Milano\PycharmProjects\MC\plots\ttkcalendar.py", line 52, in __init__
self.__place_widgets() # pack/grid used widgets
File "C:\Users\Milano\PycharmProjects\MC\plots\ttkcalendar.py", line 110, in __place_widgets
self._calendar.pack(in_=self, expand=1, fill='both', side='bottom')
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1940, in pack_configure
+ self._options(cnf, kw))
_tkinter.TclError: can't pack .34164128 inside .34161248.34161448.34161608
Do you know where is the problem?
The fault is that you don't have an __init__ method in the class CalendarDialog. So just rename the body method to __init__. Now you have initialized the instance every time one is made and a pack() method is defined.
I also encountered this problem putting a ttkCalendar into a Dialog box.
I suspect the author of this post "borrowed" the same code for building a calendar as I did:
https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=2ahUKEwiWgYWKsJ3nAhVKl3IEHYrhCU8QFjABegQICBAB&url=https%3A%2F%2Fsvn.python.org%2Fprojects%2Fpython%2Ftrunk%2FDemo%2Ftkinter%2Fttk%2Fttkcalendar.py&usg=AOvVaw0ifTox4EI7CtBFWlRYD_m9
There are two problems I found using this code to create a Calendar object and placing it into a Dialog box.
The first one causes the traceback as shown in the post. The fix is to modify the ttkcalendar.py file to pack the calendar when it is created, not after it is created using the pack() function.
Here is the diff:
102c102
< self._calendar = ttk.Treeview(show='', selectmode='none', height=7)
---
> self._calendar = ttk.Treeview(self, show='', selectmode='none', height=7)
109c109
< self._calendar.pack(in_=self, expand=1, fill='both', side='bottom')
---
> self._calendar.pack(expand=1, fill='both', side='bottom')
Once you make this change, the calendar will appear in the dialog box. However, your problems are not yet done. Another exception occurs when trying to set the minimum size of the calendar:
Exception in Tkinter callback
Traceback (most recent call last):
File "/home/richawil/Applications/anaconda3/envs/TLM/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/home/richawil/Documents/Programming/Apps/TLM/TLM/ttkcalendar.py", line 134, in __minsize
width, height = self._calendar.master.geometry().split('x')
AttributeError: 'Calendar' object has no attribute 'geometry'
I have not been able to fix this issue other than to comment out the call to self.__minsize.
63c62,63
< self._calendar.bind('<Map>', self.__minsize)
---
> # Commented out because _calendar object does not support geometry() function
> #self._calendar.bind('<Map>', self.__minsize)
I'm new to python. I'm trying to open a dialog box to get a value from within a widget that does a list of other staff allready.
But getting errors and can't figure out what to do.
Here's my code:
import Tkinter,Tkconstants,tkFileDialog
from Tkinter import *
import csv
import numpy
import math
import numpy.random as nrnd
import matplotlib.pyplot as plt
import shutil
import tkMessageBox
global filesavepath
class App:
def __init__(self,master):
self.mymaster=master
frame=Frame(master)
frame.pack()
self.importbutton=Button(frame,text='Import Data',command=self.importdata)
self.importbutton.pack()
self.executebutton=Button(frame,text='Execute',command=self.popup)
self.executebutton.pack()
self.distribution_rep=Button(frame,text='Repeat Purchase Score Distribution',command=self.distrepbutton)
self.distribution_rep.pack()
self.distribution_churn=Button(frame,text='Churn Probability Distribution',command=self.distchurnbutton)
self.distribution_churn.pack()
self.exitbutton=Button(frame,text='Exit',command=self.exitapp)
self.exitbutton.pack()
self.file_opt=options={}
options['defaultextension']=''
options['filetypes']=[('allfiles','.*'),('textfiles','.txt')]
options['initialdir']='C:\\'
options['initialfile']='myfile.txt'
options['parent']=root
options['title']='Thisisatitle'
def importdata(self):
filename=tkFileDialog.askopenfilename(**self.file_opt)
filesavepath="C:/input_full.csv"
shutil.copy2(filename,filesavepath)
if filename:
return open(filename,'r')
def popup(self):
top = self.top = Tkinter.Toplevel(self)
myLabel = Tkinter.Label(top, text='Enter your username below')
myLabel.pack()
self.myEntryBox = Tkinter.Entry(top)
self.myEntryBox.pack()
mySubmitButton = Tkinter.Button(top, text='Done', command=self.execbutton)
mySubmitButton.pack()
def execbutton(self):
if self.myEntryBox.get() != "":
self.timevalue = self.myEntryBox.get()
self.top.destroy()
execfile("Repeat Purchase Algo in python v6")
tkMessageBox.showinfo("Job Done", "Probability Computation completed")
def send(self):
global timevalue
timevalue=self.myEntryBox.get()
self.top.destroy()
def distrepbutton(self):
plt.hist(prob,bins=10,normed=TRUE)
plt.xlabel('Probability')
plt.title('Histogram of Repeat Purchase Probability')
plt.show()
def distchurnbutton(self):
plt.hist(churn_prob,bins=10,normed=TRUE)
plt.ylabel('Probability')
plt.title('Histogram of Churn Probability')
plt.show()
def exitapp(self):
self.mymaster.destroy()
root=Tk()
root.title('Repeat Puchase Widget')
app=App(root)
root.mainloop()
So as may be apparent to you, I'm importing dataset with an Import button, executing some analysis in another code through a button called Execute, and then showing some graphs.
What I wanted was to open a pop up kind of window on click of "Execute" button that will input a value. But I'm getting the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:/Python27/widget_repeat_purchase_v4", line 42, in popup
top = self.top = Tkinter.Toplevel(self)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2017, in __init__
BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1965, in __init__
BaseWidget._setup(self, master, cnf)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1943, in _setup
self.tk = master.tk
AttributeError: App instance has no attribute 'tk'
I've no idea what to do. Please help.
When you create the toplevel widget, you are passing self as the first argument. Tkinter requires that this be a parent widget. However, in your code self does not represent a widget.
In your specific case you want to pass in self.mymaster rather than self:
top = self.top = Tkinter.Toplevel(self.mymaster)
Use Tkinter.Toplevel() instead of Tkinter.Toplevel(self)