python importing file but image not recognized - python

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

Related

How should I change my tkinter code to rearrange the elements on my page?

I'm learning tkinter and getting stumped in one area. Here's the code:
from tkinter import *
from tkinter.messagebox import showinfo
def button_press():
showinfo('info','pressed button')
root = Tk()
root.geometry('800x500')
f = Frame(root)
f.pack()
Label(f, text="this is a line of text").pack(side=LEFT)
s = StringVar(value='enter here')
Entry(f, textvariable=s, width=100).pack(side=LEFT)
Button(f, text='Button', command=button_press).pack(side=RIGHT)
root.mainloop()
It produces:
But I want to align the text vertically with the entry field like this:
What do I need to change to make that happen?
Using .pack() is not advisable if you want to create more complex Frame structures.
Instead assign the items to variables and place those into a .grid().
.grid splits up your frame into different rows and columns or "sticks" them on a certain place.
below an example:
from tkinter import *
from tkinter.messagebox import showinfo
def button_press():
showinfo('info', 'pressed button')
root = Tk()
root.geometry('800x500')
f = Frame(root)
f.pack()
l1 = Label(f, text="this is a line of text")
l1.grid(row=1, column=1, sticky=W)
s = StringVar(value='enter here')
entry = Entry(f, textvariable=s, width=100)
entry.grid(row=2, column=1)
button = Button(f, text='Button', command=button_press)
button.grid(row=2, column=2)
root.mainloop()

Unable to get entry in tkinter, python

I'm new to coding and I'm trying to grab an input from an entry using tkinter in python. In theory, I should click the 'upload' button, then the code will get the entry and print it for me, but this isn't working. This is my code.
from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
def cancel():
quit()
def upload():
Entry.get()
print(Entry)
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
whitebutton = Entry(frame, fg="black")
whitebutton.pack( side = TOP)
redbutton = Button(frame, text="Cancel", fg="red", command = cancel)
redbutton.pack( side = LEFT)
bluebutton = Button(frame, text="Upload URL", fg="blue", command = upload)
bluebutton.pack( side = RIGHT )
root.mainloop()
Does anyone know what's going wrong here?
Thanks, Kieran.
Entry is a class in __init__ file in tkinter folder.
Instead of this:
Entry.get()
print(Entry)
This is what you need
var=whitebutton.get()
print(var)
First of all, it is better to use Tkinter variables rather than normal python variables. Here you need to use StringVar() to set and get an user input from entry. So the complete code -
from tkinter import *
root = Tk()
var = StringVar()
frame = Frame(root)
frame.pack()
def cancel():
quit()
def upload():
print(var.get())
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
whitebutton = Entry(frame,textvariable=var ,fg="black")
whitebutton.pack( side = TOP)
redbutton = Button(frame, text="Cancel", fg="red", command = cancel)
redbutton.pack( side = LEFT)
bluebutton = Button(frame, text="Upload URL", fg="blue", command = upload)
bluebutton.pack( side = RIGHT )
root.mainloop()
For more info - this and this
put root var before root.mainloop()
and make app var and put into "Application(root)"
then change ""root".mainloop()" to "app.mainlop()"
import tkinter as tk
// your code
root = tk.Tk()
app = Application(root)
app.mainloop()

Tkinter GUI does not respond

I'm new to programming and I'm trying to run a program that asks a user for a directory which which they will move their files to.
import tkinter as tk
from tkinter import filedialog, ttk
class Unzip():
def __init__(self):
# initialising the screen name, size title
root = tk.Tk()
root.geometry('650x550')
root.title("Move Files")
root.resizable(0, 0)
root.configure(bg='#002060')
# Initialising the frame to insert our widget
top_frame = tk.Frame(root, bg='#002060')
button_top = tk.Frame(root, bg='#002060')
button_bottom = tk.Frame(root, bg='#002060')
footer_frame = tk.Frame(root, bg='#002060')
top_frame.pack(side='top', fill='both')
button_top.pack(side='top', fill='both')
button_bottom.pack(side='top', fill='both')
footer_frame.pack(side='bottom', fill='both')
# Setting the title name
label_title = tk.Label(top_frame, text='Move Files', font='Arial 36 bold', fg='#948a54',
bg='#002060', pady=60)
label_title.pack(side='top')
# call button to get output file
output_file = ttk.Button(button_bottom, text='Choose location to save files', width=25, command=self.output_path)
output_file.pack(side='left', padx=(120, 10), pady=10)
root.mainloop()
# Get output directory
def output_path(self):
self.output_file_dir = filedialog.askdirectory()
if __name__ == '__main__':
Unzip()
The problem is that when you run the program and try to run the output_file button, the program will not be responding. I decided to use the self because I wanted it to be accessible to other instance methods that I want to create that will use the directory output_path.
So what exactly are you expecting? Your program does respond, but it is not supposed to do anything with the information.
Try
def output_path(self):
self.output_file_dir = filedialog.askdirectory()
print(self.output_file_dir)
Do you see what happens?
Maybe example 2 from this link can help you: https://www.programcreek.com/python/example/95888/tkinter.filedialog.askdirectory

New windows in tkinter

I have a bit of difficulty with the code below. Basically, I want the code to, when I press the Enter button, to open the window2 but also close window1 simultaneously so that there is only one window and not two of them.
The code is...
from tkinter import *
def window1():
window = Tk()
window.title("Welcome")
f = Frame()
f.pack()
label1 = Label(window, text = "Welcome to the random window")
label1.pack()
button1 = Button(window, text = "Enter...", command = window2)
button1.pack()
def window2():
screen = Tk()
screen.title("Pop-Up!")
fr = Frame()
fr.pack()
label2 = Label(screen, text = "This is a pop-up screen!")
label2.pack()
button2 = Button(screen, text = "Return", command = window1)
button2.pack()
window1()
This is "Bad" because you're using two instances of Tk. Try instead using TopLevels.
import tkinter as tk
def window1():
window = tk.Toplevel(root)
window.title("Welcome")
# etc etc ...
tk.Button(window,text="Enter...",command=lambda: window2(window)).pack()
def window2(old_window):
old_window.destroy()
# window2 stuff
root = tk.Tk()
root.iconify() # to minimize it, since we're just using Toplevels on top of it
window1()
root.mainloop()
When you are using the Tk() function, you are creating a new instance of the Tcl/tkinter interpreter. Instead use Toplevel() which will make a new window in the current interpreter.

NameError: name 'tkFileDialog' is not defined

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

Categories

Resources