I want to import tkFont but it's not working
from tkinter import *
import tkFont
class BuckysButtons:
def __init__(self,master):
frame = Frame(master)
frame.pack()
helv36 = tkFont.Font(family="Helvetica",size=36,weight="bold")
self.printButton = Button(frame,font=helv36, text ="Print
Message",command = self.printMessage,compound ='top')
self.printButton.pack(side =LEFT)
self.quitButton = Button(frame, text ="quit", command = frame.quit)
self.quitButton.pack(side=LEFT)
def printMessage(self):
print("It worked!")
root = Tk()
b = BuckysButtons(root)
root.mainloop()
i'm getting following error:
Traceback (most recent call last):
File "exercise.py", line 2, in <module>
import tkFont
ModuleNotFoundError: No module named 'tkFont'
It's possible you are trying to run Python 2 code under Python 3, which did some library reorganisation.
If you replace your current import with import tkinter.font as TkFont that should suffice to move you forward.
Related
I am able to get the image to display in the GUI with Tkinter however I can not get this part of the code to work as I am trying to keep it all either under one .py file because it is easier for me to keep everything in one singular window.
The error I am getting is:
Traceback (most recent call last):
File "C:/Users/Holcomb Family/PycharmProjects/webscrapeTKINTER/venv/main4.py", line 32, in <module>
run = MainWin(root)
pil_img = Image.open(my_picture)
AttributeError: type object 'Image' has no attribute 'open'
My code:
import io
from PIL import Image, ImageTk
from tkinter import *
from urllib.request import urlopen
root = tk.Tk()
root.title("New Window")
class MainWin:
def __init__(self, master):
self.master = master
url1 = "https://img.finalfantasyxiv.com/lds/pc/global/images/itemicon/"
url2 = "da/dad2c1875e87e7a7f1d02fce24f0bd0351cdda11.png?n5.45"
pic_url = url1 + url2
my_page = urlopen(pic_url)
my_picture = io.BytesIO(my_page.read())
pil_img = Image.open(my_picture)
tk_img = ImageTk.PhotoImage(pil_img)
self.label = tk.Label(root, image=tk_img)
self.label.pack(padx=5, pady=5)
root = Tk()
run = MainWin(root)
root.mainloop()
I get this error when I insert a value in the textbox.
I want to insert the date in the textbox when selecting it.
Error: _tkinter.TclError: invalid command name ".!frame.!entry"
This is my code:
main.py
from calenderUI import *
from tkinter import *
def Dateselected():
dateSelected=tkCalender()
return str(dateSelected)
def setData():
dateSel=tkCalender()
txtBoxDate.delete(0,END)
txtBoxDate.insert(0,dateSel)
return
root=Tk()
#Frame
miFrame=Frame(root,width=1200,height=2000)
miFrame.pack()
miFrame.config(bg="black")
miLabel=Label(miFrame, text="Date: ",fg="green", bg="black", font="Comic")
miLabel.grid(row=1,column=1,padx=10,pady=10)
txtBoxDate=Entry(miFrame)
txtBoxDate.grid(row=1,column=2,padx=10,pady=10,ipadx=40,ipady=2.5)
buttonDate=Button(miFrame, text="Date",command=lambda:setData())
buttonDate.grid(row=1,column=3,padx=10,pady=10)
root.mainloop()
calenderUI.py
from tkcalendar import Calendar
from tkinter import Tk
from tkinter import ttk
def tkCalender():
def print_sel():
print(cal.selection_get())
root = Tk()
cal=Calendar(root)
cal.pack()
ttk.Button(root, text="Select",command=print_sel).pack()
root.mainloop()
if __name__ == '__tkCalender__':
tkCalender()
Waiting for your help, thanks!
Error fixed, just remove root.mainloop() and some changes to insert the date in textbox (calenderUI.py)
main.py
from calenderUI import *
from tkinter import *
def Dateselected():
dateSelected=tkCalender()
return str(dateSelected)
def setData():
dateSel=tkCalender(txtBoxDate)
root=Tk()
#Frame
miFrame=Frame(root,width=1200,height=2000)
miFrame.pack()
miFrame.config(bg="black")
miLabel=Label(miFrame, text="Date: ",fg="green", bg="black", font="Comic")
miLabel.grid(row=1,column=1,padx=10,pady=10)
txtBoxDate=Entry(miFrame)
txtBoxDate.grid(row=1,column=2,padx=10,pady=10,ipadx=40,ipady=2.5)
buttonDate=Button(miFrame, text="Date",command=setData)
buttonDate.grid(row=1,column=3,padx=10,pady=10)
root.mainloop()
calenderUI.py
from tkcalendar import Calendar
from tkinter import *
dateSelected=""
def tkCalender(e):
def print_sel():
dateSelected=str(cal.selection_get())
txtBoxDate=e.delete(0,END)
txtBoxDate=e.insert(0,dateSelected)
return dateSelected
root = Tk()
cal=Calendar(root)
cal.pack()
ttk.Button(root, text="Select",command=print_sel).pack()
return str(print_sel())
if __name__ == '__tkCalender__':
tkCalender()
after going through some stack overflow and external guides still was stuck with an odd problem thread starts but function not executing but used same type of setup in unity c# and visual studio C# windows application but works there fine any help would be appreciated
import tkinter
import threading
import PIL
import time
from datetime import datetime
from PIL import Image
import pyscreenshot as ImageGrab
from tkinter import *
from tkinter import messagebox
from tkinter import Tk, Label, Button, Entry
running=False
class app:
def __init__(self, master):
self.master = master
self.thread1=threading.Thread(target=self.screenshot)
master.title("Screenshot Taker")
Label(master, text="Interval between screenshots").grid(row=0,sticky=W)
self.E1=Spinbox(master, from_ = 5, to = 1000,state = "readonly")
self.E1.grid(row=0,column=2,padx=10)
Label(master, text="File prefix").grid(row=1,sticky=W)
self.E2=Entry(master)
self.E2.grid(row=1,column=2,padx=10)
self.B1=Button(master, text="start" ,command = self.start)
self.B1.grid(row=2,column=0,columnspan=3)
self.B2=Button(master, text="stop" ,command = self.stop)
self.B2.grid(row=2,column=1,columnspan=3)
def screenshot(self):
while(running):
im=ImageGrab.grab()
dt_string = datetime.now().strftime("%d_%m_%Y_%H_%M_%S")
name=str(self.E2.get())+str(dt_string)
logging.debug(name)
im.save(name+".png")
time.sleep(int(self.E1.get()))
def start(self):
running=True
self.thread1.start()
def stop(self):
running=False
self.thread1.join()
root = Tk()
app = app(root)
root.resizable(False, False)
root.mainloop()```
To access a global variable in python, you need to use "global var_name" in each function that needs to access it:
import tkinter
import threading
import PIL
import time
from datetime import datetime
from PIL import Image
import pyscreenshot as ImageGrab
from tkinter import *
from tkinter import messagebox
from tkinter import Tk, Label, Button, Entry
running=False
class app:
def __init__(self, master):
self.master = master
self.thread1=threading.Thread(target=self.screenshot)
master.title("Screenshot Taker")
Label(master, text="Interval between screenshots").grid(row=0,sticky=W)
self.E1=Spinbox(master, from_ = 5, to = 1000,state = "readonly")
self.E1.grid(row=0,column=2,padx=10)
Label(master, text="File prefix").grid(row=1,sticky=W)
self.E2=Entry(master)
self.E2.grid(row=1,column=2,padx=10)
self.B1=Button(master, text="start" ,command = self.start)
self.B1.grid(row=2,column=0,columnspan=3)
self.B2=Button(master, text="stop" ,command = self.stop)
self.B2.grid(row=2,column=1,columnspan=3)
def screenshot(self):
global running
while(running):
im=ImageGrab.grab()
dt_string = datetime.now().strftime("%d_%m_%Y_%H_%M_%S")
name=str(self.E2.get())+str(dt_string)
logging.debug(name)
im.save(name+".png")
time.sleep(int(self.E1.get()))
def start(self):
global running
running=True
self.thread1.start()
def stop(self):
global running
running=False
self.thread1.join()
root = Tk()
app = app(root)
root.resizable(False, False)
root.mainloop()
I have constructed an application, the source starts like this:
from tkinter import Text
from tkinter import Label
from AESEncDec import *
from MD5Hashing import *
from RSAEncDec import *
color = 'lightblue' #color our background
class Application(Frame):
def __init__(self, root=None):
Frame.__init__(self, root)
self.frame_width = 700
self.frame_height = 400
But last piece of it cannot execute:
#create object TK class
the_window = Tk(className = " Cryptographic")
#create object Application
app = Application(the_window)
#run our Application
app.mainloop()
And it gives the NameError:
Traceback (most recent call last):
File "/home/artur/Documents/MScProject/MSc Project/Task #179276/main_program.py", line 169, in
the_window = Tk(className = " Cryptographic")
NameError: name 'Tk' is not defined
How should I define it properly in this case?
You miss an import statement : from tkinter import Tk
The best way to avoid conflict, is to import the whole module, eventually with an alias to make it short (but don't forget to add tk. everywhere you've called a tkinter widget):
import tkinter as tk
from AESEncDec import *
from MD5Hashing import *
from RSAEncDec import *
color = 'lightblue' #color our background
class Application(tk.Frame):
def __init__(self, root=None):
tk.Frame.__init__(self, root)
self.frame_width = 700
self.frame_height = 400
#create object TK class
the_window = tk.Tk(className = " Cryptographic")
#create object Application
app = Application(the_window)
#run our Application
app.mainloop()
Hey I'm following a tutorial, https://www.youtube.com/watch?v=a1Y5e-aGPQ4 , and I can't get it to work properly. I'm trying to add an image when you press on a menu button:
from tkinter import *
from PIL import *
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
self.init_Window()
def init_Window(self):
self.master.title("GUI")
self.pack(fill =BOTH, expand=1)
#quitButton = Button(self, text = "Quit", command = self.client_exit)
#quitButton.place(x=0,y=0)
menu = Menu(self.master)
self.master.config(menu=menu)
file=Menu(menu)
file.add_command(label='Save',command= self.client_exit)
file.add_command(label='Exit',command= self.client_exit)
menu.add_cascade(label='File',menu=file)
edit = Menu(menu)
edit.add_command(label='Show Image', command=self.showImg)
edit.add_command(label='Show Text', command=self.showTxt)
menu.add_cascade(label='Edit',menu=edit)
def showImg(self):
load = Image.open('Pic.png')
render = ImageTk.PhotoImage(load)
img = Label(self, image=render)
img.image = render
img.place(x=0,y=0)
def showTxt(self):
text = Label(self,text='Hey')
text.pack
def client_exit(self):
exit()
root = Tk()
root.geometry("400x300")
app = Window(root)
root.mainloop()
I have tried asking around school, StackOverflow, and YouTube for about 3 days now, and nothing has solved my problem, if you need any more info about it please ask. I am getting the error code:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1558, in __call__
return self.func(*args)
File "/root/Desktop/Python Programs/Tkinter.py", line 35, in showImg
load = Image.open('pic.png')
AttributeError: type object 'Image' has no attribute 'open'
You use import * so you don't know if you use tkinter.Image or PIL.Image . And this is why you shouldn't use import *
Try
from PIL import Image, ImageTk
Images are a bit tricky to get right, some tips: Keep the image object global, to avoid garbage collection, avoid Attribute Error (by reading the docs).
In this example I don t use PIL and I load a gif image
#!/usr/bin/python
#-*-coding:utf-8 -*
#Python 3
#must have a valid gif file "im.gif" in the same foldeer
from tkinter import *
Window=Tk()
ListePhoto=list()
ListePhoto.append(PhotoImage(file="im.gif"))
def Try():
Window.title('image')
Window.geometry('+0+0')
Window.configure(bg='white')
DisplayImage()
def DisplayImage():
label_frame=LabelFrame(Window, relief='ridge', borderwidth=12, text="AnImage",
font='Arial 16 bold',bg='lightblue',fg='black')
ListeBouttons=list()#Liste Vide pour les Radiobutton(s)
RadioButton = Radiobutton(label_frame,text="notext",image=ListePhoto[0], indicatoron=0)
RadioButton.grid(row=1,column=1)
label_frame.pack(side="left")
if __name__ == '__main__':
Try()