That's my code and I have a proplem with config() method it dosen't work with me when I use it with canvas it give me this error:
AttributeError: 'int' object has no attribute 'config'
so please help me because I stuck here....
from tkinter import ttk
from tkinter import filedialog
root = Tk()
root.title('3R')
root.geometry('350x300')
root.columnconfigure(0, weight=1)
myCanvas = Canvas(root, width=350, height=300)
myCanvas.pack(fill='both', expand=True)
#File location
Folder_Name =""
def openLocation():
global Folder_Name
Folder_Name = filedialog.askdirectory()
if(len(Folder_Name))>1:
LocError.config(text=Folder_Name, fg='green')
else:
LocError.config(text='Please Choose Folder!!',fg = 'red')
LocError = myCanvas.create_text(175,120, text='You must select a location',fill='red', font=('jost', 10))
#Button for location
SaveLoc = Button(root, text='Choose Path', command = openLocation)
myCanvas.create_window(130,87, anchor='nw', window=SaveLoc)
root.mainloop()```
You have to change your if statement as follows:
if len(Folder_Name) > 1:
myCanvas.itemconfig(LocError,text=Folder_Name, fill='green')
else:
myCanvas.itemconfig(LocError,text='Please Choose Folder!!',fill='red')
itemconfig takes an id or tag of the canvas item and edits the properties of it. Also there is no fg option for text of canvas, so change that to fill.
This is the working code:
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
root = Tk()
root.title("3R")
root.geometry("350x300")
root.columnconfigure(0, weight=1)
myCanvas = Canvas(root, width=350, height=300)
myCanvas.pack(fill='both', expand=True)
#File location
Folder_Name = ""
def openLocation():
global Folder_Name, myCanvas, LocError
Folder_Name = filedialog.askdirectory()
myCanvas.delete(LocError) # Delete the old sprite
if len(Folder_Name) > 1:
# Create a new sprite with the correct parameters:
LocError = myCanvas.create_text(175, 120, text=Folder_Name, fill="green", font=("jost", 10))
else:
# Create a new sprite with the correct parameters:
LocError = myCanvas.create_text(175, 120, text="Please Choose Folder!!", fill="red", font=("jost", 10))
LocError = myCanvas.create_text(175, 120, text="You must select a location", fill="red", font=("jost", 10))
#Button for location
SaveLoc = Button(root, text="Choose Path", command=openLocation)
myCanvas.create_window(130, 87, anchor="nw", window=SaveLoc)
root.mainloop()
The variable LocError is an int. It is used to identify the sprite (for the text). To change it, I deleted it and created a new one with the correct text/fill.
Related
I'm trying to run this code but it's giving "_tkinter.TclError: bad window path name ".!button2" " this error.
But If I run the same code without ebook function, it's working fine. As I'm new to coding, any help will be appreciated.
from tkinter import *
root = Tk()
root.title("Application")
root.resizable(width=False, height=False)
mylabel0= Label(root, text=" ")
mylabel0.grid(row=0, column=0)
def ebook():
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from gtts import gTTS
import pdfplumber
book = tk.Tk()
book.minsize(width=150, height=200)
book.maxsize(width=300, height=420)
canvas1 = tk.Canvas(book, width=300, height=420, bg='azure3', relief='raised')
canvas1.grid()
label1 = tk.Label(book, text="PDF Audio Store", bg='azure3')
label1.config(font=('helvetica', 16))
canvas1.create_window(150, 20, window=label1)
final = ""
def get_pdf():
global final
global pdf_checker
try:
import_file_path = filedialog.askopenfilename()
if (str(import_file_path).endswith(".pdf")):
pdf = pdfplumber.open(import_file_path)
pdf_checker = pdf
n = len(pdf.pages)
for page in range(n):
data = pdf.pages[page].extract_text()
final = final + "\n" + data
messagebox.showinfo("Information", "PDF is imported")
else:
raise Exception("Provide .pdf file only")
except Exception as e:
messagebox.showerror("Error", "{}".format(e))
else:
print("Continue to conversion")
brows_pdf = tk.Button(text="PDF entry", command=get_pdf, bg='royalblue', fg="white", font=('helvetica', 12, 'bold'),
border=0,
activebackground="green")
It's giving error in this(👇) area specifically, create_window.Error Image
canvas1.create_window(150, 60, window=brows_pdf)
def convert_audio():
global final
global pdf_checker
try:
print("File Information")
print(pdf_checker)
export_file_path = filedialog.asksaveasfilename(defaultextension=".mp3")
final_file = gTTS(text=final, lang="en")
final_file.save(export_file_path)
messagebox.showinfo("Information", "Audio file generated")
except NameError:
messagebox.showwarning("Warning", "Import PDF first")
audio_button = tk.Button(text="Convert to Audio", command=convert_audio, bg='royalblue', fg="white",
font=('helvetica', 12, 'bold'),
border=0,
activebackground="green")
canvas1.create_window(150, 100, window=audio_button)
book.mainloop()
button_ebook= Button(root, text="E-Book📖", font=30, padx=25, pady=25, command=ebook, fg="black", bg="white", borderwidth=1)
button_ebook.grid(row=3, column=2, padx=10)
root.mainloop()
The root of the problem is that you can't use a button in one window that is a descendant of another window.
The first problem is that you are creating two instances of Tk. Buttons created in one instance are not available in the other. In this case, your button is in the original instance of Tk but your canvas is in the other.
The second problem is similar. Even when replacing the second instance of Tk, the button is in the root window and thus can't be used as a child of the canvas which is in the second window.
The solution is to use Toplevel for the second window, and to make sure the button is a descendant of the second window and/or the canvas.
I'm trying to open a Turtle window from a GUI to select a position on the image with a mouse click. The x and y coordinates are then returned as an input to the GUI.
Here is a minimal working example:
from tkinter import *
from tkinter import font as tkFont
import turtle
xclick = 0
yclick = 0
def callback3():
getcoordinates()
def getcoordinates():
screen = turtle.Screen()
screen.setup(400, 400)
screen.bgpic("stunden.gif")
screen.onscreenclick(modifyglobalvariables)
def modifyglobalvariables(rawx,rawy):
global xclick
global yclick
xclick = int(rawx//1)
yclick = int(rawy//1)
print(xclick)
print(yclick)
turtle.bye()
root = Tk()
helv30 = tkFont.Font(family='Helvetica', size=30)
button1 = Button(root, text = "1", width=3, font=helv30, borderwidth=0, command=callback3)
button1.grid(row=0, column=0, padx=5, pady=0)
root.mainloop()
Then the error image "pyimage2" doesn't exist shows up. I found out, that it has something to do with two instances of Tk, as there is the root and the turtle window and that I should solve it with Toplevel(). However, after hours of research and try and error I still could not come up with the right solution to make my code work. Any help is greatly appreciated.
Here's how to implement it directly in tkinter — so no turtle module required — as I suggested earlier in a (now-deleted) comment:
from tkinter import *
from tkinter import font as tkFont
CLOCK_IMAGE_PATH = 'clock.png'
xclick, yclick = 0, 0
def callback3():
window = Toplevel()
window.title("Stunden")
img = PhotoImage(file=CLOCK_IMAGE_PATH)
img_width, img_height = img.width(), img.height()
window.minsize(width=img_width, height=img_height)
canvas = Canvas(window, width=img_width, height=img_height)
canvas.pack()
canvas.image = img # Keep reference to avoid image being garbage collected.
canvas.create_image(0, 0, anchor='nw', image=img)
canvas.bind("<Button-1>", get_coordinates) # Set up event-handler callback.
def get_coordinates(event):
global xclick, yclick
xclick = int(event.x // 1)
yclick = int(event.y // 1)
print(f'xclick={xclick}, yclick={yclick}')
root = Tk()
helv30 = tkFont.Font(family='Helvetica', size=30)
button1 = Button(root, text="1", width=3, font=helv30, borderwidth=0, command=callback3)
button1.grid(row=0, column=0, padx=5, pady=0)
root.mainloop()
So over here I am trying to make a little python-tkinter program which will store your passwords of your apps in files. However, when I try to make the second screen open, I get this error:
TypeError: 'Toplevel' object is not callable
Here is the code:
from tkinter import *
from tkinter import messagebox
import os
def screen2():
global screen2
screen2 = Toplevel(root)
screen2.title("Main Page")
screen2.geometry("260x230")
screen2.resizable("False","False")
Label(screen2, text="hello").pack()
def check_code():
code_requestget = code_request.get()
print(code_requestget)
if code_requestget == code:
screen2()
else:
messagebox.showwarning("Error", "Code is incorrect")
def mainscreen():
global root
global code
global code_request
code = "1234"
root = Tk()
root.title("Passwords")
root.geometry("260x230")
root.resizable("False","False")
code_request = StringVar()
label1 = Label(root, text="Welcome - Enter Code", width="40", height="3", background="SpringGreen3")
label1.pack()
Label(text="").pack()
enter_code = Entry(root, width="20", textvariable=code_request)
enter_code.pack()
Label(text="").pack()
continue_button = Button(root, text="Continue", width="16", command=check_code)
continue_button.pack()
root.mainloop()
mainscreen()
Unrelated to your question, but seeing your window names makes me think you don't want to use Toplevel at all. That's only needed when you want 2 active windows, but I suspect you want to use one window just to check the password, then close it and open a second, "main" window, right? If so you need to reconfigure the root window instead of using Toplevel to open a new window. Like this:
from tkinter import *
from tkinter import messagebox
import os
def screen2():
frame1.destroy() # remove all the pw check stuff
root.title("Main Page") # rename window
Label(root, text="hello").pack()
def check_code():
code_requestget = code_request.get()
print(code_requestget)
if code_requestget == code:
screen2()
else:
messagebox.showwarning("Error", "Code is incorrect")
def mainscreen():
global root, code, code_request, frame1
code = "1234"
root = Tk()
root.title("Passwords")
root.geometry("260x230")
root.resizable("False","False")
frame1 = Frame(root) # create a Frame to hold pw check components
frame1.pack()
code_request = StringVar()
label1 = Label(frame1, text="Welcome - Enter Code", width="40", height="3", background="SpringGreen3")
label1.pack()
Label(frame1, text="").pack()
enter_code = Entry(frame1, width="20", textvariable=code_request)
enter_code.pack()
Label(frame1, text="").pack()
continue_button = Button(frame1, text="Continue", width="16", command=check_code)
continue_button.pack()
root.mainloop()
mainscreen()
I'm creating a GUI in python using tkinter and am having trouble when running it. I have an entry box widget, a radiobutton widget, and a button widget. When I press the button, what I want is the user to type a number into the entry box and select an option from the list of radiobuttons. When the user presses the button, I'd like the values to be retrieved and displayed in the other frame for testing. What I get instead is when the button gets pressed, I get the error 'NoneType' object has no attribute 'get'. The error is referring to the value inside of the entry box: self.tune_entry
The code I have is as follows:
SA_main.py
import os
import tkinter as tk
from tkinter import ttk
from tkinter import font
import SA_gui
def main():
x_vals = [0,1,2,3,4]
y_vals = [0,1,2,3,4]
root = SA_gui.tk.Tk()
UI = SA_gui.Window(root, x_vals, y_vals)
root.mainloop()
if __name__ == "__main__":
main()
SA_gui.py
import os
import tkinter as tk
from tkinter import ttk
from tkinter import font
# Class to define, setup, and build the GUI
class Window:
# Dimensions of the GUI
HEIGHT = 600
WIDTH = 1200
# Colors for main layout
bg_color = "#B0E0E6"
frame_color1 = "#73B1B7"
white_color = "#FFFFFF"
def __init__(self, master, x_vals, y_vals):
# Take in the lists of files for later use
self.x_vals = x_vals
self.y_vals = y_vals
#--------------------------------------------------------------
# Define and create the window
self.master = master
master.title("Signal Analysis")
master.geometry("{}x{}".format(Window.WIDTH, Window.HEIGHT))
# Create and place the background frame
self.bg_frame = tk.Frame(self.master, bg=Window.bg_color, bd=5)
self.bg_frame.place(relwidth=1, relheight=1)
# Create the main title
self.main_title = tk.Label(self.bg_frame, text="Software Defined Radio Signal Analysis",
bg=Window.bg_color, font=("Courier", 14))
self.main_title.pack(side="top")
#--------------------------------------------------------------
# Create and place the frame for tuning
self.tune_frame = tk.Frame(self.bg_frame, bg=Window.frame_color1, bd=4)
self.tune_frame.place(relx=0.05, rely=0.1, relwidth=0.2428, relheight=0.8)
# Create and place the title for the tuning frame
self.tune_title = tk.Label(self.tune_frame, text="Tune", bg=Window.frame_color1, font=
("Courier", 11))
self.tune_title.place(relwidth=1, anchor="nw")
# Create and place the contents of the tuning frame
self.tune_cont = tk.Frame(self.tune_frame, bg=Window.white_color, bd=4)
self.tune_cont.place(relx=0.05, rely=0.05, relwidth=0.9, relheight=0.925)
#Label for frequency entry
self.tune_label = tk.Label(self.tune_cont, text='Enter carrier frequency: (kHz)',
bg=Window.white_color)
self.tune_label.place(relx=0.025, rely=0)
#Entry Box for frequency entry
self.tune_entry = tk.Entry(self.tune_cont)
self.tune_entry.place(relx=0.025, rely=0.075, relwidth=0.95, relheight=0.05)
#Label for divider
self.tune_div = ttk.Separator(self.tune_cont, orient="horizontal")
self.tune_div.place(rely=0.175, relwidth=1)
#Label for display mode
self.disp_label = tk.Label(self.tune_cont, text='Select Display:', bg=Window.white_color)
self.disp_label.place(relx=0.025, rely=0.2)
#Variable for radiobuttons
self.var = tk.IntVar(self.tune_cont).set("1")
#Radio Button for Spectral Analysis
self.SA_select = tk.Radiobutton(self.tune_cont, text="Spectral
Analysis",bg=Window.white_color, padx=20, variable=self.var, value=1)
self.SA_select.place(relx=0.025, rely=0.275)
#Radio Button for Option 2
self.opt2_select = tk.Radiobutton(self.tune_cont, text="Option 2",bg=Window.white_color,
padx=20, variable=self.var, value=2)
self.opt2_select.place(relx=0.025, rely=0.35)
#Radio Button for Option 3
self.opt3_select = tk.Radiobutton(self.tune_cont, text="Option 3",bg=Window.white_color,
padx=20, variable=self.var, value=3)
self.opt3_select.place(relx=0.025, rely=0.425)
#Button for selection
self.tune_button = ttk.Button(self.tune_cont, text="Enter", command=lambda:
self.print_selected(self.var.get(), self.tune_entry.get()))
self.tune_button.place(relx= 0.775, rely=0.9, relwidth=0.2, relheight=0.075)
#-----------------------------------------------------------------
# Create and place the frame for the plot
self.plot_frame = tk.Frame(self.bg_frame, bg=Window.frame_color1, bd=4)
self.plot_frame.place(relx=0.3428, rely=0.1, relwidth=0.6071, relheight=0.8)
# Create and place the title for the plot frame
self.plot_title = tk.Label(self.plot_frame, text="Plot", bg=Window.frame_color1, font=
("Courier", 11))
self.plot_title.place(relwidth=1, anchor="nw")
# Create and place the contents of the plot frame
self.plot_cont = tk.Frame(self.plot_frame, bg=Window.white_color, bd=4)
self.plot_cont.place(relx=0.025, rely=0.05, relwidth=0.95, relheight=0.925)
def print_selected(self, disp, freq):
if disp == 1:
disp_mode = "Spectral Analysis"
elif disp == 2:
disp_mode = "Option 2"
else:
disp_mode = "Option 3"
#Label for this test
self.prnt_label = tk.Label(self.plot_cont, text="Display: " + disp_mode + ", Center Freq: " +
freq, bg=Window.white_color)
self.prnt_label.place(relx=0.025, rely=0.2)
Any help to resolve this issue is greatly appreciated!
Consider this code:
self.var = tk.IntVar(self.tune_cont).set("1")
Anytime you do x=y().z() python assigns the return value of z() to x. Thus, in your code you're assiging the result of .set("1") to self.var. The set method is returning None so self.var is None. Thus, when you later try to call self.var.get() it's the same as doing None.get().
If you want to initialize a variable at the time of creation, there is no need to call set. Also, while it works to pass a string, if you're setting an IntVar you really ought to be setting it to an integer.
self.var = tk.IntVar(value=1)
Im always on my project on tkinter and i have created a border function to create a rectangle with a specificate border, anyway my problem its my entry is behind my rectangle how can i change it ??
its is my code:
def SetBorder(event):
Border(window, 120, 21, 20, bg_color_hex, border_color_hex, 3)
def NewProject():
global window
window = tk.Toplevel(frame)
window.title("New Project")
window.geometry("720x480")
window.resizable(0, 0)
window.config(bg=bg_color_hex)
Project_Name_Label = Label(window, text="Project Name:")
Project_Name_Label.place(x=15, y=20)
Project_Name_Label.config(fg=text_color_hex, bg=bg_color_hex)
global Project_Name_Entry
Project_Name_Entry = Entry(window, width=20)
Project_Name_Entry.config(bg=entry_color, bd=0, fg=text_color_hex)
Project_Name_Entry.bind("<Button-1>", SetBorder)
Project_Name_Entry.place(x=120, y=21)