I'm trying to use Tkinter and get the user to choose a certain file. My code looks like this (I'm just starting out with Tkinter)
from Tkinter import *
from tkFileDialog import *
root = Tk()
root.wm_title("Pages to PDF")
root.wm_iconbitmap('icon.ico')
w = Label(root, text="Please choose a .pages file to convert.")
y = tkFileDialog.askopenfilename(parent=root)
y.pack()
w.pack()
root.mainloop()
When I run the program, I get an error that says:
NameError: name 'tkFileDialog' is not defined
I've tried it with a few configurations I found online. None of them have worked; but this is the same basic error every time. How can I fix this?
You are importing everything from tkFileDialog module, so you don't need to write a module-name prefixed tkFileDialog.askopenfilename(), just askopenfilename(), like:
from Tkinter import *
from tkFileDialog import *
root = Tk()
root.wm_title("Pages to PDF")
w = Label(root, text="Please choose a .pages file to convert.")
fileName = askopenfilename(parent=root)
w.pack()
root.mainloop()
Try this:
from Tkinter import *
import tkFileDialog
root = Tk()
root.wm_title("Pages to PDF")
root.wm_iconbitmap('icon.ico')
w = Label(root, text="Please choose a .pages file to convert.")
y = tkFileDialog.askopenfilename(parent=root)
y.pack()
w.pack()
root.mainloop()
Seems a space name problem.
Try this:
try:
import Tkinter as tk
import tkFileDialog as fd
except:
import tkinter as tk
from tkinter import filedialog as fd
def NewFile():
print("New File!")
def OpenFile():
name = fd.askopenfilename()
print(name)
def About():
print("This is a simple example of a menu")
class myGUI:
def __init__(self, root):
self.root = root
self.canvas = tk.Canvas(self.root,
borderwidth=1,
relief="sunken")
self.canvas.pack( fill=tk.BOTH, expand=tk.YES)
self.menu = tk.Menu(self.root)
self.root.config(menu=self.menu)
self.helpmenu = tk.Menu(self.menu)
self.filemenu = tk.Menu( self.menu )
self.menu.add_cascade(label="File", menu=self.filemenu)
self.filemenu.add_command(label="New", command=NewFile)
self.filemenu.add_command(label="Open...", command=OpenFile)
self.filemenu.add_separator()
self.filemenu.add_command(label="Exit", command=root.destroy)
root = tk.Tk()
root.title('appName')
myGUI(root)
root.mainloop()
Related
I'm trying to use the theme "sun valley" for a python-based installer that i'm working on. I have all the .tcl files installed and everything should be working, but its not. I even tried to use the built in styles
here's my code:
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
import os
director = os.path.dirname(__file__)
friendlyName = "python"
file = ""
import shutil
global User
try:
User = os.getlogin()
except:
User="home"
from tkinter import *
from tkinter import filedialog
from os import path
path = fr"C:\{User}\AppData\Local\{friendlyName}"
def install():
try:
os.mkdir(path)
except:
pass
shutil.copy(file, path)
#E1 = Entry(top, bd =5)
window = Tk()
# Just simply import the azure.tcl file
style = ttk.Style(window)
dir_path = os.path.dirname(os.path.realpath(__file__))
window.tk.call('source', os.path.join(dir_path, 'theme\dark.tcl'))
print(os.path.join(dir_path, 'theme\dark.tcl'))
#window.tk.call("set_theme", "dark")
style.theme_use('sun-valley-dark')
window.geometry("600x400")
window.rowconfigure(20)
window.columnconfigure(20)
def askdir():
direct = filedialog.askdirectory()
path = direct
textBox.delete(0, END)
textBox.insert(0, path)
#textBox.set(path)
window.update_idletasks()
window.title(f"{friendlyName} install")
chooseText = Label(window, text=f"choose a place for {friendlyName} to be installed")
chooseText.grid(column=2, row=0)
chooseButton = Button(window, text="choose path", command=askdir)
chooseButton.grid(column=1, row=3)
textBox = Entry(window, text=f"{path}")
textBox.insert(0, path)
textBox.grid(column=2, row=3)
chooseButton = Button(window, text="install", command=install)
chooseButton.grid(column=3, row=4)
chooseButton = Button(window, text="quit", command=window.destroy)
chooseButton.grid(column=1, row=4)
window.mainloop()
heres what outputs:
Need to use ttk widgets
instead of chooseText = Label(window, text=f"choose a place for {friendlyName} to be installed")
it would be chooseText = ttk.Label(window, text=f"choose a place for {friendlyName} to be installed")
then the style will show up!
I have created one python file with a drowdown menu. When i choose the option one, it imports another python file, with a checkbutton and a picture in a canvas. Both files and the picture are located in the same folder. The code import the file imports the canvas and the checkbutton, but I get the error saying image "pyimage1" doesn't exist. If I run that second file alone, it does show the checkbutton and the image without errors. When Import a python file the images are not recognized anymore or am I doing something wrong? is any workaround there?
main program:
from tkinter import *
root = Tk()
root.geometry('1560x750')
canvas=Canvas(root)
canvas.config(width=1000, height=1560, bg='light grey')
canvas.grid(row=1,column=3, rowspan=1550,ipadx=1300,ipady=750,sticky=NW)
def option_number(x):
if x == "one":
import part2
variable = StringVar()
variable.set("options")
w = OptionMenu(canvas, variable, "one", "two",command = option_number)
w.config(width=15, height=1,bg='blue')
w.place(x=400,y=100)
root.mainloop()
file to be imported:
from tkinter import *
root = Tk()
root.geometry('1560x750')
canvas=Canvas(root)
canvas.config(width=1000, height=1560, bg='light grey')
canvas.grid(row=1,column=3, rowspan=1550,ipadx=1300,ipady=750,sticky=NW)
button = Checkbutton(canvas).place(x=170, y=230)
AND_gate=PhotoImage(file='AND.png') #set up variables for and_gate
labelimage_and = Label(canvas, image=AND_gate).place(x=200,y=200)
root.mainloop()
Updated code to import function:
from tkinter import *
root = Tk()
root.geometry('1560x750')
canvas=Canvas(root)
canvas.config(width=1000, height=1560, bg='light grey')
canvas.grid(row=1,column=3, rowspan=1550,ipadx=1300,ipady=750,sticky=NW)
def option_number(x):
if x == "one":
from part1 import import_def
variable = StringVar()
variable.set("options")
w = OptionMenu(canvas, variable, "one", "two",command = option_number)
w.config(width=15, height=1,bg='blue')
w.place(x=400,y=100)
root.mainloop()
file where is the function to be imported:
from tkinter import *
root = Tk()
def import_def():
root = Toplevel()
root.geometry('1560x750')
canvas2 = Canvas(root)
canvas2.config(width=1000, height=1560, bg='red')
canvas2.grid(row=1, column=3, rowspan=1550, ipadx=1300, ipady=750, sticky=NW)
button = Checkbutton(canvas2).place(x=170, y=230)
AND_gate=PhotoImage(file='AND.png') #set up variables for and_gate
labelimage_and = Label(canvas2, image=AND_gate).place(x=200,y=200)
root.mainloop()
This is the way that I know on how to import files and functions within tkinter, not sure if this is the right way but take a look at the changes I made to both the files
main.py:
from tkinter import *
from function import import_def
root = Tk()
root.geometry('1560x750')
canvas=Canvas(root)
canvas.config(width=1000, height=1560, bg='light grey')
canvas.grid(row=1,column=3, rowspan=1550,ipadx=1300,ipady=750,sticky=NW)
def option_number(x):
if x == "one":
import_def()
variable = StringVar()
variable.set("options")
w = OptionMenu(canvas, variable, "one", "two",command = option_number)
w.config(width=15, height=1,bg='blue')
w.place(x=400,y=100)
root.mainloop()
and function.py:
from tkinter import *
def import_def():
root = Toplevel()
root.geometry('1560x750')
canvas2 = Canvas(root)
canvas2.config(width=1000, height=1560, bg='red')
canvas2.grid(row=1, column=3, rowspan=1550, ipadx=1300, ipady=750, sticky=NW)
button = Checkbutton(canvas2).place(x=170, y=230)
AND_gate=PhotoImage(file='sad songs.jpg') #set up variables for and_gate
labelimage_and = Label(canvas2, image=AND_gate).place(x=200,y=200)
root.mainloop()
Hope it was of some help, do let me know if any doubts or errors.
Cheers
How do ask a string and a integer question in a single simpledialogbox in tkinter without opening another simpledialogbox
from tkinter import *
from tkinter import simpledialog
simpledialog. askstring("name", "what is your name ")
Mainloop()
You could use Toplevel() to create your own version of a simpledialog, something like the below:
from tkinter import *
class App:
def __init__(self, root):
self.root = root
self.button1 = Button(self.root, text="Ok", command=self.drawtop)
self.button1.pack()
def drawtop(self):
self.top = Toplevel(root)
self.entry1 = Entry(self.top)
self.entry2 = Entry(self.top)
self.button2 = Button(self.top, text="Done", command=self.printtop)
self.entry1.pack()
self.entry2.pack()
self.button2.pack()
def printtop(self):
print(self.entry1.get())
print(self.entry2.get())
self.top.destroy()
root = Tk()
App(root)
root.mainloop()
I'm just starting to use tkinter and it is a little difficult to handle it. Check this sample :
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import Tkinter as tk
import tkFileDialog
def openfile():
filename = tkFileDialog.askopenfilename(title="Open file")
return filename
window = tk.Tk()
tk.Button(window, text='Browse', command=openfile).pack()
window.mainloop()
I juste created a browse button which keep the file path in the variable "filename" in the function openfile(). How can i put the content of "filename" in a variable out of the function ?
For example I want to put it in the variable P and print it in a terminal
def openfile():
filename = tkFileDialog.askopenfilename(title="Open file")
return filename
window = tk.Tk()
tk.Button(window, text='Browse', command=openfile).pack()
window.mainloop()
P = "the file path in filename"
print P
I also also want to put the file path in a widget Entry(), and as same as below, get the text in the Entry widget in another global variable.
If someone knows, it would be nice.
There are at least two different ways of doing it:
1) Bundle your whole app in a class like this:
import Tkinter as tk
import tkFileDialog
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self) # create window
self.filename = "" # variable to store filename
tk.Button(self, text='Browse', command=self.openfile).pack()
tk.Button(self, text='Print filename', command=self.printfile).pack()
self.spinbox = tk.Spinbox(self, from_=0, to=10)
self.spinbox.pack(pady=10)
tk.Button(self, text='Print spinbox value', command=self.printspinbox).pack()
self.mainloop()
def printspinbox(self):
print(self.spinbox.get())
def openfile(self):
self.filename = tkFileDialog.askopenfilename(title="Open file")
def printfile(self):
print(self.filename)
if __name__ == '__main__':
App()
In this case, filename is an attribute of the App, so it is accessible from any function inside the class.
2) Use a global variable:
import Tkinter as tk
import tkFileDialog
def openfile():
global filename
filename = tkFileDialog.askopenfilename(title="Open file")
def printfile():
print(filename)
def printspinbox():
print(spinbox.get())
window = tk.Tk()
filename = "" # global variable
tk.Button(window, text='Browse', command=openfile).pack()
tk.Button(window, text='Print filename', command=printfile).pack()
spinbox = tk.Spinbox(window, from_=0, to=10)
spinbox.pack(pady=10)
tk.Button(window, text='Print spinbox value', command=printspinbox).pack()
window.mainloop()
I am new to trying this TKinter . I have to browse files and folders. What i need is to get the pathname of the files and folders i have browsed. i Am not not able to understand where to put my piece of code in this script? . How can i do it? or should i write a seperate . Am stuck in here. I browsed through stack overflow many have problem of getting filenames returned back to their program s with no proper solution. Can anyone help me on this?Advance thanks.
from Tkinter import Tk, RIGHT, BOTH, RAISED,Label
from ttk import Frame, Button, Style
from PIL import Image, ImageTk
import tkFileDialog
import tkMessageBox
import glob
#global root
f1=""
f2=""
def FileBrowser():
img1_path = tkFileDialog.askopenfilename(parent=root,title='Provide the Query Image ')
global f1
f1=img1_path
#print img1_path
def PathBrowser():
img2_path =tkFileDialog.askdirectory(parent=root,title='Provide the path for Training Dataset ')
global f2
f2=img2_path
#print img2_path
def matcher():
imlist=glob.glob(f2)
print imlist
for file in imlist:
print file
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
global root
self.parent.title("Medical CBIR")
self.style = Style()
self.style.theme_use("default")
frame = Frame(self, relief=RAISED, borderwidth=1)
w = Label(self, text="QUERY IMAGE")
w.pack()
style = Style()
style.configure("TFrame", background="#333")
im = Image.open('D:/database/Mixture/1.png')
img = ImageTk.PhotoImage(im)
label1 = Label(self, image=img)
label1.image = img
label1.place(x=155, y=70)
frame.pack(fill=BOTH, expand=1)
self.pack(fill=BOTH, expand=1)
Retrieve_Image=Button(self,text="Retrieve Related Images",command=matcher)
Retrieve_Image.pack(side=RIGHT, padx=5, pady=5)
Training_Image = Button(self, text="Path of Training Images",command=PathBrowser)
Training_Image.pack(side=RIGHT, padx=5, pady=5)
Test_image = Button(self,text="Browse Test_Image",command=FileBrowser)
Test_image.pack(side=RIGHT, padx=5, pady=5)
def main():
global root
root = Tk()
#root.geometry("300x200+300+300")
root.geometry("500x500")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
# Comparison.py(2nd file)
import cv2
import sys
import GUItkinter
img1_path =GUITKinter.FileBrowser()
img2_path =GUITKinter.PathBrowser()
imlist=glob.glob(f2)
for file in imlist:
compare(img1_path,file) #Function to compare images for similarity
#display the retrieved results
Error: Bad window pathname in img1_path =GUITKinter.FileBrowser()
You have to work out the code yourself. But what I'll do is provide you a way how to format your code & how to implement the problem you are having.
import tkFileDialog
from Tkinter import Tk,Button,StringVar,Entry
class MainClass():
def __init__(self,master):
self.parent=master
self.mainfunc()
def mainfunc(self):
self.path_setup = StringVar()
browse=Button(root,text="Browse",command=lambda:self.path_setup.set(tkFileDialog.askopenfilename(filetypes=[("Image File",'.jpg')])))
browse.grid(row=1,column=1,sticky='E')
path_entry = Entry(root, textvariable=self.path_setup,state='disabled')
path_entry.grid(row=1,column=0,sticky='E')
if __name__ == '__main__':
root = Tk()
root.title("My Program")
root.wm_resizable(0,0)
client = MainClass(root)
root.mainloop()
It's a "piece" of code which I was working on. I have formatted it for you.
Hope this gets you going :)