Reputation:
I'm coding a Tkinter, which much consist of a checkbox and File Menu containing Save Option.
Problem: It comes in 2 tkinter instead of one. One is a blank GUI, and another consists of my checkbox, textbox, file and save.
How to avoid the blank GUI?
My code:
from Tkinter import *
import Tkinter
from tkFileDialog import askopenfile, asksaveasfile
import tkFileDialog
class myproject(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self)
self.textbox()
self.checkbox2()
def textbox(self):
self.txt1 = Tkinter.Text(root, borderwidth=3, relief="sunken", height=4,width=55)
self.txt1.config(font=("consolas", 12), undo=True, wrap='word')
self.txt1.grid(row=0, column=1, sticky="nsew", padx=2, pady=2)
def checkbox2(self): #self.checkbox
checkbox = Tkinter.Checkbutton(root, text = " ")
checkbox.grid(column=1,row=2)
def file_save(self):
f = asksaveasfile(mode='w', defaultextension=".txt")
root = Tkinter.Tk()
menubar = Menu(root)
root.configure(menu=menubar)
filemenu = Menu(menubar,tearoff=0)
menubar.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Save", command=myproject.file_save)
app = myproject(None)
app.mainloop()
Upvotes: 2
Views: 6765
Reputation: 18821
I reworked your code to make it work.
What was changed: You had 2 variables root
and app
, one of which was creating the blank window. I changed it to just use a single variable root
, which is initialized to myproject
at the start.
Instead of using root
in your functions, I changed those to self
, because self
inherits from Tkinter.Tk
as well.
And in the __init__
function, I removed the variable parent
which was unused.
Update: Also in the call to filemenu.add_command, it is changed to pass in root.file_save instead of myproject.file_save. Thanks PM 2Ring.
from Tkinter import *
import Tkinter
from tkFileDialog import askopenfile, asksaveasfile
import tkFileDialog
class myproject(Tkinter.Tk):
def __init__(self):
Tkinter.Tk.__init__(self)
self.textbox()
self.checkbox2()
def textbox(self):
self.txt1 = Tkinter.Text(self, borderwidth=3, relief="sunken", height=4,width=55)
self.txt1.config(font=("consolas", 12), undo=True, wrap='word')
self.txt1.grid(row=0, column=1, sticky="nsew", padx=2, pady=2)
def checkbox2(self): #self.checkbox
checkbox = Tkinter.Checkbutton(self, text = " ")
checkbox.grid(column=1,row=2)
def file_save(self):
f = asksaveasfile(mode='w', defaultextension=".txt")
root = myproject()
menubar = Menu(root)
root.configure(menu=menubar)
filemenu = Menu(menubar,tearoff=0)
menubar.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Save", command=root.file_save)
root.mainloop()
Upvotes: 3