i'm trying to make this simple gui using grid layout where i have in one row a label an entry and a button, but for some reason the first button always takes the rowspan equal to the number of rows in previous column, even if i try to force it to have rowspan 1 it has no effect which makes me really confused.
import tkinter as tk
class MainApplication(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.grid()
#LABELS
self.l1 = tk.Label(self, text = "Source")
self.l1.grid(column = 0, row = 0, sticky = "E")
self.l2 = tk.Label(self, text = "Text files destination")
self.l2.grid(column = 0, row = 1, sticky = "E")
self.l3 = tk.Label(self, text = "Image files destination")
self.l3.grid(column = 0, row = 2, sticky = "E")
#ENTRIES
self.e1 = tk.Entry(self)
self.e1.grid(column = 1, row = 0)
self.e2 = tk.Entry(self)
self.e2.grid(column = 1, row = 1)
self.e3 = tk.Entry(self)
self.e3.grid(column = 1, row = 2)
#BUTTONS
self.b3 = tk.Button(text = "Select dir", command = self.cb2)
self.b3.grid(column = 2, row = 0)
self.b4 = tk.Button(text = "Select dir", command = self.cb2)
self.b4.grid(column = 2, row = 1)
self.b5 = tk.Button(text = "Select dir", command = self.cb2)
self.b5.grid(column = 2, row = 2)
if __name__ == "__main__":
root = tk.Tk()
app = MainApplication(root)
root.mainloop()
output:
http://i.imgur.com/AdWkHwi.png
You don't specify a parent for the buttons, so their parent is the root window. The labels and entries, on the other hand, have their parent attribute set to the frame. What happens is that in the root, the frame is in row zero, and the first button is in row zero, and the height of the row is determined by the height of the frame.
The solution is to make the parent of the buttons be the frame.
self.b3 = tk.Button(self, ...)
self.b4 = tk.Button(self, ...)
self.b5 = tk.Button(self, ...)
Related
So, what i wanna do is that when i click the button, a new thing to be added to my project.
I have few tabs, and on the second one (WorkExp) I got Company and job description labels, and i want that whenever i click the button it to add new same labels.
it works, the button, but the thing is add the placement on these new labels is the same as old ones.
I tried while and for cycle but i couldnt make any of them work.
What I have tried:
WorkExp = ttk.Frame(Tabs)
Tabs.add(WorkExp, text = "Work Experience")
######################
def AddExp():
Label(WorkExp, text = "Company/Place", padx = 5, pady = 5).grid(row = 3, column = 1)
Label(WorkExp, text="Job Description", padx=5, pady=5).grid(row = 4 , column=1)
Comp2 = Entry(WorkExp).grid(row=3, column=2)
Work2 = Entry(WorkExp).grid(row=4, column=2)
######################
Label(WorkExp, text = "Company/Place", padx = 5, pady = 5).grid(row = 1, column = 1)
Label(WorkExp, text = "Job Description", padx = 5, pady = 5).grid(row = 2, column = 1)
Comp1 = Entry(WorkExp).grid(row = 1, column = 2)
Work1 = Entry(WorkExp).grid(row = 2, column = 2)
Button(WorkExp, text = "Add Experience", command = AddExp).grid(row = 10, column = 1)
import Tkinter as tk
# Now Start From Here
class App(object):
def new_row(self):
# Create widgets -----
new_entry = tk.Entry(root, width=7)
# Put widgets in grid----------
self.num_rows += 1
new_entry.grid(column=0, row=self.num_rows, sticky='WE')
def __init__(self):
self.num_rows = 1
createRow_button = tk.Button(
root, text='New Row', command=self.new_row)
createRow_button.grid()
root = tk.Tk()
app = App()
root.mainloop()
I'm trying to make a text editor with Python 3.4.2 and tkinter/ttk. When my file is loaded in, the text is inserted into the Text widget from the bottom of the file up, making the file text "backwards". The last line of the file is inserted first, and the first line last. Anything will help. Thank you.
from tkinter import *
from tkinter import ttk
import os
class Main(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.body = Text(self, width=50, height=15)
self.body.grid(row = 0, column = 0, sticky = W)
self.save_label = Label(self, text="File to Save to:")
self.save_label.grid(row = 2, column = 0, sticky = W)
self.save_entry = ttk.Entry(self)
self.save_entry.grid(row = 3, column = 0, sticky = W)
self.save_button = ttk.Button(self, text="Save File", command=self.save)
self.save_button.grid(row = 4, column = 0, sticky = W)
self.read_label = Label(self, text="File to Read:")
self.read_label.grid(row = 2, column = 1, sticky = W)
self.read_entry = ttk.Entry(self)
self.read_entry.grid(row = 3, column = 1, sticky = W)
self.read_button = ttk.Button(self, text="Read File", command=self.read)
self.read_button.grid(row = 4, column = 1, sticky = W)
scrollbar = ttk.Scrollbar(root, orient=VERTICAL, command=self.body.yview)
scrollbar.grid(row = 0, column = int(1), sticky = 'ns')
self.body.config(yscrollcommand=scrollbar.set)
self.quit_button = ttk.Button(self, text="Quit", command=self.close)
self.quit_button.grid(row = 5, column = 0, sticky = W)
def close(self):
root.destroy()
quit()
def save(self):
body = self.body.get('0.0', 'end-1c')
file = self.save_entry.get()
file = open(file, "w")
file.write(body)
file.close()
def read(self):
self.body.delete("0.0", END)
file = self.read_entry.get()
file = open(file, 'r')
file_data = file.readlines()
for i in file_data:
self.body.insert('1.0', str(i))
file.close()
root = Tk()
root.title("NotePad")
root.geometry("500x600")
root.attributes("-fullscreen", True)
app = Main(root)
root.mainloop()
You are telling tkinter to place each line at "1.0". If you want each line to be added to the end, use "end"
for i in file_data:
self.body.insert('end', str(i))
By the way, the first character of a text widget is at "1.0", not "0.0". While "0.0" will work as quirk of how tkinter is implemented, the correct index is "1.0".
For example, use this:
body = self.body.get('1.0', 'end-1c')
... rather than this:
body = self.body.get('0.0', 'end-1c')
I'm new to Python and just started venturing into doing GUIs. I created a Tkinter window that is pretty basic: it has 3 Entry bars and 3 File Dialog buttons. When you chose the 3rd directory, the GUI file automatically makes a call to a separate file and receives a large text block which is then displayed in a Text box.
The whole thing works correctly, but my problem is that after receiving and inserting the text response, Tkinter stops working and doesn't allow the user to scroll down.
I read that one reason this happens is because people use both .pack( ) and .grid( ), but I'm not mixing those two functions.
Thanks in advance for any help!
Here's my GUI file
from tkinter import *
from tkinter import filedialog
from gui_GPSExtractor import *
import os
class Application(Frame):
def __init__(self, master):
""" Initialize Frame """
Frame.__init__(self, master)
self.grid( )
self.startGUI( )
""" Create Labels, Text Boxes, File Dialogs, and Buttons """
def startGUI(self):
# Label for Scan Path
self.dLabel = Label(self, text = "Scan Path")
self.dLabel.grid(row = 0, column = 0, columnspan = 2, sticky = W)
# Entry for Scan Path
self.dEntry = Entry(self, width = 60)
self.dEntry.grid(row = 1, column = 0, sticky = W)
# Button for Scan Path Directory Browse
self.dButton = Button(self, text = "Browse", command = lambda: self.browseFiles("d"))
self.dButton.grid(row = 1, column = 1, sticky = W)
# Label for CSV Path
self.cLabel = Label(self, text = "CSV Path")
self.cLabel.grid(row = 3, column = 0, columnspan = 2, sticky = W)
# Entry for CSV Path
self.cEntry = Entry(self, width = 60)
self.cEntry.grid(row = 4, column = 0, sticky = W)
# Button for CSV Path Directory Browse
self.cButton = Button(self, text = "Browse", command = lambda: self.browseFiles("c"))
self.cButton.grid(row = 4, column = 1, sticky = W)
# Label for Log Path
self.lLabel = Label(self, text = "Log Path")
self.lLabel.grid(row = 6, column = 0, columnspan = 2, sticky = W)
# Entry for Log Path
self.lEntry = Entry(self, width = 60)
self.lEntry.grid(row = 7, column = 0, sticky = W)
# Button for Log Path Directory Browse
self.lButton = Button(self, text = "Browse", command = lambda: self.browseFiles("l"))
self.lButton.grid(row = 7, column = 1, sticky = W)
# Text Box for Results
self.resultText = Text(self, width = 60, height = 30, wrap = WORD, borderwidth = 3, relief = SUNKEN)
self.resultText.grid(row = 9, column = 0, columnspan = 2, sticky = "nsew")
# Scrollbar for Text Box
self.scrollBar = Scrollbar(self, command = self.resultText.yview)
self.scrollBar.grid(row = 9, column = 2, sticky = "nsew")
self.resultText["yscrollcommand"] = self.scrollBar.set
def browseFiles(self, btnCalling):
if(btnCalling == "d"):
self.dName = filedialog.askdirectory(initialdir = "/python3-CH05")
self.dEntry.delete(0, END)
self.dEntry.insert(0, self.dName)
elif(btnCalling == "c"):
self.cName = filedialog.askdirectory(initialdir = "/python3-CH05")
self.cEntry.delete(0, END)
self.cEntry.insert(0, self.cName)
elif(btnCalling == "l"):
self.lName = filedialog.askdirectory(initialdir = "/python3-CH05")
self.lEntry.delete(0, END)
self.lEntry.insert(0, self.lName)
output = extractGPS(self.dName, self.cName, self.lName)
self.resultText.delete(0.0, END)
self.resultText.insert(0.0, output)
# Start the GUI
root = Tk( )
root.title("Python gpsExtractor")
root.geometry("650x650")
app = Application(root)
root.mainloop( )
I am making a maze where the user enters the dimensions and can then click on a button to change the colour of that button to black. What i eventually want is to be making an ai which will try to navigate the maze the user created with the black rectangle the ai not being allowed to go on.
The problem is i dont know how to change the properties of the button clicked as due to a nested loop being used for creation they all have the same name.
from tkinter import *
import tkinter as tk
from tkinter.ttk import Combobox,Treeview,Scrollbar
class MainMenu(Frame):
def __init__(self, master):
""" Initialize the frame. """
super(MainMenu, self).__init__(master)
self.grid()
self.frame1 = tk.LabelFrame(self, text="entering diemsions", width=300, height=130, bd=5)
self.frame1.grid(row=0, column=0, columnspan=3, padx=8)
self.frame2 = tk.LabelFrame(self, text="creating maze", width=300, height=130, bd=5)
self.frame2.grid(row=1, column=0, columnspan=3, padx=8)
self.create_GUI()
def create_GUI(self):
self.width_lbl = Label(self.frame1, text = "width:")
self.width_lbl.grid(row = 1 , column = 1)
self.width_txt = Entry(self.frame1)
self.width_txt.grid(row = 1, column = 2)
self.getdimensions_btn = Button(self.frame1, text = "enter dimensions",command = lambda:self.createmaze())
self.getdimensions_btn.grid(row = 1 , column = 3)
self.height_lbl = Label(self.frame1, text = "height:")
self.height_lbl.grid(row = 1 , column = 4)
self.height_txt = Entry(self.frame1)
self.height_txt.grid(row = 1, column = 5)
def createmaze(self):
width = int(self.width_txt.get())
height = int(self.height_txt.get())
for widthcount in range (width):
for heightcount in range(height):
self.maze_btn = Button(self.frame2, text = "",width = 4, height = 2)
self.maze_btn.grid(row = heightcount , column = widthcount)
self.maze_btn.bind("<Button-1>", self.disablebtn)
def disablebtn(self,event):
grid_info = event.widget.grid_info()
col = grid_info["column"]
col = int(col)
row = grid_info["row"]
row = int(row)
root = Tk()
root.title("hi")
root.geometry("500x500")
root.configure(bg="white")
app = MainMenu(root)
root.mainloop()
I'm working on the GUI for a simple quiz app using Tkinter in Python 2.7.
Thus far, I have begun to set up my frame. I've put a scrollbar inside of a Text widget named results_txtbx to scroll up and down a list noting the player's performance on each question. I've been using grid since it's easier for me to manage.
from Tkinter import *
class Q_and_A:
def __init__(self, master):
frame = Frame(master)
Label(master).grid(row = 4)
results_txtbx = Text(master)
results_scrbr = Scrollbar(results_txtbx)
results_scrbr.grid(sticky = NS + E)
results_txtbx.config(width = 20, height = 4, wrap = NONE, yscrollcommand = results_scrbr.set)
results_txtbx.grid(row = 3, column = 1, padx = 12, sticky = W)
root = Tk()
root.wm_title("Question and Answer")
root.resizable(0, 0)
app = Q_and_A(root)
root.mainloop()
What happens is that when it runs, results_txtbx resizes to fit the scrollbar. Is there any way to make it keep its original size using grid?
You don't want to use a text widget as the master for a scrollbar. Like any other widget, if you pack or grid the scrollbar in the text widget, the text widget will shrink or expand to fit the scrollbar. That is the crux of your problem.
Instead, create a separate frame (which you're already doing), and use that frame as the parent for both the text widget and the scrollbars. If you want the appearance that the scrollbars are inside, set the borderwidth of the text widget to zero, and then give the containing frame a small border.
As a final usability hint, I recommend not making the window non-resizable. Your users probably know better what size of window they want than you do. Don't take that control away from your users.
Here's (roughly) how I would implement your code:
I would use import Tkinter as tk rather than from Tkinter import * since global imports are generally a bad idea.
I would make Q_and_A a subclass of tk.Frame so that it can be treated as a widget.
I would make the whole window resizable
I would separate widget creation from widget layout, so all my layout options are in one place. This makes it easier to write and maintain, IMO.
As mentioned in my answer, I would put the text and scrollbar widgets inside a frame
Here's the final result:
import Tkinter as tk
class Q_and_A(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master, borderwidth=1, relief="sunken")
self.label = tk.Label(self)
self.results_txtbx = tk.Text(self, width=20, height=4, wrap="none",
borderwidth=0, highlightthickness=0)
self.results_scrbr = tk.Scrollbar(self, orient="vertical",
command=self.results_txtbx.yview)
self.results_txtbx.configure(yscrollcommand=self.results_scrbr.set)
self.label.grid(row=1, columnspan=2)
self.results_scrbr.grid(row=0, column=1, sticky="ns")
self.results_txtbx.grid(row=0, column=0, sticky="nsew")
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
root = tk.Tk()
root.wm_title("Question And Answer")
app = Q_and_A(root)
app.pack(side="top", fill="both", expand=True)
root.mainloop()
Set results_scrbr.grid(row = 3, column = 2) next to results_txtbx.grid(row = 3,column = 1, padx = 4), sticky is not needed because window is not resizable, and i lowered the padx so scrollbar is closer to text.
Also to make the results_txtbx vertically scrollable, add results_scrbr.config(command=results_txtbx.yview)
Here is a working code...
from Tkinter import *
class Q_and_A:
def __init__(self, master):
frame = Frame(master)
Label(master).grid(row = 4)
results_txtbx = Text(master)
results_scrbr = Scrollbar(master)
results_scrbr.grid(row = 3, column = 2)
results_scrbr.config(command=results_txtbx.yview)
results_txtbx.config(width = 20, height = 4,
wrap = NONE, yscrollcommand = results_scrbr.set)
results_txtbx.grid(row = 3, column = 1, padx = 4)
root = Tk()
root.wm_title("Question and Answer")
root.resizable(0, 0)
app = Q_and_A(root)
root.mainloop()
My implemented solution:
I needed to add more widgets to the app, so I bound the Scrollbar and Text widgets to another label and put that in the proper column the code (trimmed for readability) is below:
import Tkinter as tk
class Q_and_A(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.label = tk.Label(self)
#Set up menu strip
self.main_menu = tk.Menu(self)
self.file_menu = tk.Menu(self.main_menu, tearoff = 0)
self.file_menu.add_command(label = "Exit", command = self.quit)
self.main_menu.add_cascade(label = "File", menu = self.file_menu)
self.master.config(menu = self.main_menu)
#Set up labels
self.question_lbl = tk.Label(self, text = "Question #: ", padx = 12, pady = 6)
self.question_lbl.grid(row = 0, sticky = "w")
tk.Label(self, text = "Hint: ").grid(row = 1, sticky = "w", padx = 12, pady = 6)
tk.Label(self, text = "Answer: ").grid(row = 2, sticky = "w", padx = 12, pady = 6)
tk.Label(self, text = "Results: ").grid(row = 3, sticky = "nw", padx = 12, pady = 6)
tk.Label(self).grid(row = 4)
#Set up textboxes
self.question_txtbx = tk.Entry(self)
self.question_txtbx.config(width = 60)
self.question_txtbx.grid(row = 0, column = 1, padx = 12, columnspan = 3, sticky = "w")
self.help_txtbx = tk.Entry(self)
self.help_txtbx.config(width = 40)
self.help_txtbx.grid(row = 1, column = 1, columnspan = 2, padx = 12, sticky = "w")
self.answer_txtbx = tk.Entry(self)
self.answer_txtbx.config(width = 40)
self.answer_txtbx.grid(row = 2, column = 1, columnspan = 2, padx = 12, sticky = "w")
self.results_label = tk.Label(self)
self.results_txtbx = tk.Text(self.results_label, width = 10, height = 4, wrap = "none", borderwidth = 1, highlightthickness = 1)
self.results_scrbr = tk.Scrollbar(self.results_label, orient = "vertical", command = self.results_txtbx.yview)
self.results_txtbx.configure(yscrollcommand = self.results_scrbr.set)
self.label.grid(row = 1)
self.results_label.grid(row = 3, column = 1, padx = 11, sticky = "w")
self.results_scrbr.grid(row = 0, column = 1, sticky = "nse")
self.results_txtbx.grid(row = 0, column = 0, sticky = "w")
root = tk.Tk()
root.wm_title("Question and Answer")
#A note: The window is non-resizable due to project specifications.
root.resizable(0, 0)
app = Q_and_A(root)
app.pack(side = "top", fill = "both")
root.mainloop()
I'll keep storage in nested labels as a reference for myself for when I need to group things close together, unless there's some reason it should be avoided. Worked very well here. Thanks to Bryan for the advice.