Thanks all for your suggestions. Adding self. before calling my functions fixed that issue. I'm now running into a different issue where the stored procedure I am using isn't getting properly read into the pandas dataframe. I don't get any errors, the tkinter window pops up like it should, but when the PDF gets generated, there is no data in the rows, just the column names and other formatting I've written in.
I added print(df) to the code to check if it was an issue with the data getting read from the dataframe to the PDF, but print(df) just returns Empty DataFrame.
from tkinter import *
import pyodbc
import pandas as pd
from reportlab.lib import colors
from reportlab.platypus import *
from reportlab.lib import styles
from reportlab.lib.units import inch
# Create connection
server = 'XXXXXXX'
database = 'XXXXXXX'
username = 'XXXXXXXX'
password = 'XXXXXXXXX'
try:
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+password+'')
except:
raise NameError('unable to connect')
#save stored procedure to a global variable
storedProc = 'EXEC [presentation].[pdf_project] '
elements = []
class NewPDF:
def __init__(self):
window = tk.Tk()
window.title("Form Example")
window = tk.Frame(window)
window.grid(column=0,row=0, sticky=(tk.N,tk.W,tk.E,tk.S))
window.columnconfigure(0, weight = 1)
window.rowconfigure(0, weight = 1)
window.pack(pady = 100, padx = 100)
self.tkvar = tk.StringVar(window)
choices = {'2021','2020','2019','2018'}
self.tkvar.set('2021')
popupMenu = tk.OptionMenu(window, self.tkvar, *choices)
tk.Label(window, text = "Pick Year").grid(row = 1, column = 1)
popupMenu.grid(row = 1, column = 2)
tk.Label(window, text = "Customer").grid(row = 2, column = 1)
self.e1 = tk.Entry(window)
self.e1.grid(row = 2, column = 2)
self.param_year = self.tkvar.get()
self.param_cust = str(self.e1.get())
B = tk.Button(window, text = "Make PDF", command=self.make_df_and_pdf()).grid(row = 3, column = 1)
self.tkvar.trace('w', self.change_dropdown())
window.mainloop()
def change_dropdown(self, *args):
print(args)
def make_df_and_pdf(self):
#param_year = self.tkvar.get()
#param_cust = str(self.e1.get())
params = "'" + self.param_cust + "'," + self.param_year + ""
querystring = storedProc + params
df = pd.read_sql_query(querystring, cnxn)
lista = [df.columns[:,].values.astype(str).tolist()] + df.values.tolist()
#cust_list = (df['CUSTOMER'].unique())
#cust_list = cust_list.tolist()
#print(df)
styles = getSampleStyleSheet()
ts = [('ALIGN', (1,1), (-1,1), 'LEFT'),
('BOX', (0,0), (3,0), 2, colors.red),
('FONT', (0,0), (-1,0), 'Times-Bold'),
('GRID', (0,1), (-1,-1), 0.5, colors.grey)]
n_table = Table(lista, colWidths = (1.5*inch, 1.5*inch, 1.5*inch, 1.5*inch, 1.5*inch), repeatRows = 1)
table_style = TableStyle(ts)
n_table.setStyle(table_style)
PATH_OUT = "Desktop"
doc = SimpleDocTemplate(PATH_OUT + 'UserInputPDF_Test.pdf')
elements.append(Paragraph("CustomerTAT", styles['Title']))
elements.append(n_table)
doc.build(elements)
NewPDF()
EDIT: The stored procedure operates as it should within SQL. Here is the code for my stored procedure:
USE [XXXXX]
GO
/****** Object: StoredProcedure [presentation].[pdf_project] Script Date: 6/22/2021 4:31:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: XXXXXX
-- Create date:
-- Description:
-- =============================================
ALTER PROCEDURE [presentation].[pdf_project]
-- Add the parameters for the stored procedure here
#CustomerName varchar(50) = '',
#Year int = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT CUSTOMER, [TAT Whole Days], [SHIP DATE], YEAR([SHIP DATE]) AS YEAR,
CASE
WHEN MONTH([SHIP DATE]) IN (1,2,3) THEN 'Q1'
WHEN MONTH([SHIP DATE]) IN (4,5,6) THEN 'Q2'
WHEN MONTH([SHIP DATE]) IN (7,8,9) THEN 'Q3'
ELSE 'Q4'
END AS QUARTER
FROM presentation.CustomerTAT
WHERE (YEAR([SHIP DATE]) = #Year or YEAR([SHIP DATE]) = #Year)
AND CUSTOMER = #CustomerName
END
Related
To give some background, I am attempting to use Python to give some of my users an interface through a third-party program (that already has IronPython embedded) to add, edit, and delete records from a SQL Server database.
I've received good assistance from one member here about Python .NET Winforms so I am attempting to get some more assistance. My goal is to populate a DataGridView (dgv) with records from a table. Seems pretty simple. However, when I run the code, my dgv is just an empty container.
I could use some assistance or better yet, point me in the right direction to find the answer. I am willing to learn.
import clr
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
clr.AddReference("System.Data")
clr.AddReference("System.Globalization")
from System.Windows.Forms import *
from System.Drawing import *
from System.Data import *
from System.Data.SqlClient import *
from System.Globalization import *
class MyForm(Form):
def __init__(self):
# Setup the form
self.Text = "Calculated Control Limits Form"
self.StartPosition = FormStartPosition.CenterScreen # https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.startposition?view=net-5.0
# Create & configure the DataGridView label
self.setupDataGridViewLabel()
# Create, configure, and populate data for the DataGridView
self.setupDataGridView()
self.PopulateDataGridView("SELECT * FROM SPC_CALCULATED_CONTROL_LIMITS")
# Create & configure a line seperator
self.setupSeperator()
# Create & configure a Label to grab the users Employee ID
self.setupEmployeeIDLabel()
# Create & configure a label for the Lower Control Limit Label
self.Load_LCL_Label()
# Create & configure a TextBox for the Lower Control Limit
self.Load_LCL_TextBox()
# Create & configure a label for the Target Mean
self.LoadTargetMeanLabel()
# Create & configure a TextBox for the Target Mean
self.LoadTargetMeanTextBox()
# Create & configure a label for the Upper Control Limit
self.Load_UCL_Label()
# Create & configure a TextBox for the Upper Control Limit
self.Load_UCL_TextBox()
# Create & configure a label for the Comment
self.LoadCommentLabel()
# Create a TextBox for the Comment
self.LoadCommentTextBox()
# Create & configure the button
self.LoadButton()
# Register the event handler
self.button.Click += self.button_Click
self.Size = Size (550, self.button.Bottom + self.button.Height + 15)
#Load the Controls to the Form
self.Controls.Add(self.lblCCL)
self.Controls.Add(self.dgvCCL)
self.Controls.Add(self.button)
self.Controls.Add(self.lblSep)
self.Controls.Add(self.lblEmpID)
self.Controls.Add(self.lblLCL)
self.Controls.Add(self.txtLCL)
self.Controls.Add(self.lblTarget)
self.Controls.Add(self.txtTarget)
self.Controls.Add(self.lblUCL)
self.Controls.Add(self.txtUCL)
self.Controls.Add(self.lblComment)
self.Controls.Add(self.txtComment)
def button_Click(self, sender, args):
self.Close()
def setupDataGridView(self):
self.dgvCCL = DataGridView()
self.dgvCCL.AllowUserToOrderColumns = True
self.dgvCCL.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
self.dgvCCL.Location = Point(self.lblCCL.Left, self.lblCCL.Bottom + 5)
self.dgvCCL.Size = Size(500, 250)
self.dgvCCL.TabIndex = 3
#self.dgvCCL.ColumnCount = len(headers)
self.dgvCCL.ColumnHeadersVisible = True
def setupSeperator(self):
self.lblSep = Label()
self.lblSep.Size = Size(500, 2)
self.lblSep.BackColor = Color.DarkGray
self.lblSep.BorderStyle = BorderStyle.Fixed3D
self.lblSep.Location = Point(self.dgvCCL.Left, self.dgvCCL.Bottom + 10)
def setupDataGridViewLabel(self):
self.lblCCL = Label()
self.lblCCL.Text = "Calculated Control Limits View"
self.lblCCL.Font = Font(self.Font, FontStyle.Bold)
self.lblCCL.Location = Point(10, 10)
self.lblCCL.BorderStyle = 0 # BorderStyle.None --> https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.borderstyle?view=net-5.0
self.lblCCL.Size = Size(self.lblCCL.PreferredWidth, self.lblCCL.PreferredHeight)
def setupEmployeeIDLabel(self):
self.lblEmpID = Label()
self.lblEmpID.Text = 'login.computeruser.upper()'
self.lblEmpID.Font = Font(self.Font, FontStyle.Bold)
self.lblEmpID.Size = Size(self.lblEmpID.PreferredWidth, self.lblEmpID.PreferredHeight)
self.lblEmpID.Location = Point(self.dgvCCL.Right - self.lblEmpID.Width, self.dgvCCL.Top - 15)
self.lblEmpID.BorderStyle = 0
def Load_LCL_Label(self):
self.lblLCL = Label()
self.lblLCL.Text = 'Lower Control Limit'
self.lblLCL.Size = Size(self.lblLCL.PreferredWidth, self.lblLCL.PreferredHeight)
self.lblLCL.Location = Point(self.lblSep.Left + 65, self.lblSep.Top + 15)
self.lblLCL.BorderStyle = 0
def Load_LCL_TextBox(self):
self.txtLCL = TextBox()
self.txtLCL.Size = Size(100, 50)
self.txtLCL.Location = Point(self.lblLCL.Left, self.lblLCL.Bottom + 3)
def LoadTargetMeanLabel(self):
self.lblTarget = Label()
self.lblTarget.Text = 'Target Mean'
self.lblTarget.Size = Size(self.lblLCL.PreferredWidth, self.lblLCL.PreferredHeight)
self.lblTarget.Location = Point(self.lblLCL.Left + 125, self.lblSep.Top + 15)
self.lblTarget.BorderStyle = 0
def LoadTargetMeanTextBox(self):
self.txtTarget = TextBox()
self.txtTarget.Size = Size(100, 50)
self.txtTarget.Location = Point(self.lblLCL.Left + 125, self.lblLCL.Bottom + 3)
def Load_UCL_Label(self):
self.lblUCL = Label()
self.lblUCL.Text = 'Upper Control Limit'
self.lblUCL.Size = Size(self.lblUCL.PreferredWidth, self.lblUCL.PreferredHeight)
self.lblUCL.Location = Point(self.lblTarget.Left + 125, self.lblSep.Top + 15)
self.lblUCL.BorderStyle = 0
def Load_UCL_TextBox(self):
self.txtUCL = TextBox()
self.txtUCL.Size = Size(100, 50)
self.txtUCL.Location = Point(self.lblTarget.Left + 125, self.lblLCL.Bottom + 3)
def LoadCommentLabel(self):
self.lblComment = Label()
self.lblComment.Text = 'Comment'
self.lblComment.Size = Size(self.lblUCL.PreferredWidth, self.lblUCL.PreferredHeight)
self.lblComment.Location = Point(self.lblSep.Left, 350)
self.lblComment.BorderStyle = 0
def LoadCommentTextBox(self):
self.txtComment = TextBox()
self.txtComment.Multiline = True
self.txtComment.Size = Size(500, 50)
self.txtComment.Location = Point(self.lblSep.Left, self.lblComment.Bottom + 5)
def LoadButton(self):
self.button = Button()
self.button.Size = Size(100, 30)
self.button.Location = Point(self.lblSep.Left, self.txtComment.Bottom + 10)
self.button.Text = "Click Me!"
def PopulateDataGridView(self, selectcommand):
bs = BindingSource()
try:
connectionstring = "YourSQLServerConnectionString"
# Create a new data adapter based on the specified query.
da = SqlDataAdapter(selectcommand, connectionstring)
# Create a command builder to generate SQL update, insert, and delete commands based on selectCommand.
cb = SqlCommandBuilder(da)
# Populate a new data table and bind it to the BindingSource.
dt = DataTable()
Locale = CultureInfo.InvariantCulture
da.Fill(dt)
bs.DataSource = dt
# Resize the DataGridView columns to fit the newly loaded content.
self.dgvCCL.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader)
#String connectionString =
#"Data Source=<SQL Server>;Initial Catalog=Northwind;" +
#"Integrated Security=True";
#// Create a new data adapter based on the specified query.
#dataAdapter = new SqlDataAdapter(selectCommand, connectionString);
#// Create a command builder to generate SQL update, insert, and
#// delete commands based on selectCommand.
#SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
#// Populate a new data table and bind it to the BindingSource.
#DataTable table = new DataTable
#{
# Locale = CultureInfo.InvariantCulture
#};
#dataAdapter.Fill(table);
#bindingSource1.DataSource = table;
#// Resize the DataGridView columns to fit the newly loaded content.
#dataGridView1.AutoResizeColumns(
#DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
except SqlException:
Messagebox.Show("Something happened.")
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(MyForm())
I am writing a simple program for a local business that will allow its users to easily keep track of their job service tickets. At one point, I had the program working with no errors. However, being that I am very new to programming and had typed a lot of messy code, I went back and decided to clean some of it up, as well as added better functionality. In doing so, I caused an error to occur, and I can't seem to fix it.
I have tried multiple ways to solve this issue, but all I have been able to determine is that if I remove a small block of code, it will essentially run as it should.
Here are the two definitions:
def gui_elements_remove(self, elements):
for element in elements:
element.destroy()
def Load(self):
self.gui_elements_remove(self.gui_elements)
var = self.FirstTree.focus()
treevar = self.FirstTree.item(var)
JobDF = pd.DataFrame(treevar, index = [0])
self.JobID = JobDF.iloc[0]['values']
cursor1 = self.cursor.execute("SELECT * from 'Service Tickets' WHERE JobID = ?", (self.JobID))
SP = cursor1.fetchall()
df = pd.DataFrame(SP, columns = [
'ServiceTicketsID',
'JobID',
'Ticket Number',
'Reason for Visit',
'Warranty/VPO',
'Date Ticket Received',
'Date of Service',
'Service Person'
])
columns = [
'ServiceTicketsID',
'Ticket Number',
'Reason for Visit',
'Warranty/VPO',
'Date Ticket Received',
'Date of Service',
'Service Person'
]
LoadFrame = Frame(self.root)
LoadFrame.pack(fill = BOTH, expand = True, padx = 50)
scroll = Scrollbar(LoadFrame, orient = VERTICAL)
SecondTree = ttk.Treeview(LoadFrame, yscrollcommand = scroll.set, columns = columns)
SecondTree['show'] = 'headings'
SecondTree.heading('#1', text = 'ServiceTicketsID')
SecondTree.heading('#2', text = 'Ticket Number')
SecondTree.heading('#3', text = 'Reason for Visit')
SecondTree.heading('#4', text = 'Warranty/VPO')
SecondTree.heading('#5', text = 'Date Ticket Received')
SecondTree.heading('#6', text = 'Date of Service')
SecondTree.heading('#7', text = 'Service Person')
SecondTree.column('#1', width = 0, stretch = NO)
SecondTree.column('#2', width = 75, stretch = YES, anchor = "n")
SecondTree.column('#3', width = 75, stretch = YES, anchor = "n")
SecondTree.column('#4', width = 75, stretch = YES, anchor = "n")
SecondTree.column('#5', width = 100, stretch = YES, anchor = "n")
SecondTree.column('#6', width = 100, stretch = YES, anchor = "n")
SecondTree.column('#7', stretch = YES, anchor = "n")
scroll.config(command = SecondTree.yview)
scroll.pack(side = RIGHT, fill = Y)
SecondTree.pack(fill = BOTH, expand = TRUE)
Maintree = df [[
'ServiceTicketsID',
'Ticket Number',
'Reason for Visit',
'Warranty/VPO',
'Date Ticket Received',
'Date of Service',
'Service Person'
]]
Maintree_rows = Maintree.to_numpy().tolist()
for row in Maintree_rows:
SecondTree.insert("", 0, values = row)
for col in columns:
SecondTree.heading(col, text=col, command=lambda _col=col: \
self.Treeview_sort_column(SecondTree, _col, False))
b1 = Button(LoadFrame, text = "Add")
b2 = Button(LoadFrame, text = "Update")
b3 = Button(LoadFrame, text = "Cancel")
b1.configure(command = lambda: self.Load_Add())
b2.configure(command = lambda: self.Load_Update())
#b3.configure(command = lambda: self.Cancel_Button(LoadFile, self.MainWindow, self.root))
b1.pack(side = LEFT, padx = 5, pady = 50)
b2.pack(side = LEFT, padx = 5, pady = 50)
b3.pack(side = LEFT, padx = 5, pady = 50)
There is more code but what I've provided should be more than enough, hopefully. The first method is called to clear out the frame from the previous method being run. The remainder is supposed to take the user's selection from the previous TreeView. However, upon running this code, I am given the error
_tkinter.TclError: invalid command name ".!frame3.!treeview"
If I comment out this block of code:
var = self.FirstTree.focus()
treevar = self.FirstTree.item(var)
JobDF = pd.DataFrame(treevar, index = [0])
self.JobID = JobDF.iloc[0]['values']
cursor1 = self.cursor.execute("SELECT * from 'Service Tickets' WHERE JobID = ?", (self.JobID))
SP = cursor1.fetchall()
df = pd.DataFrame(SP, columns = [
'ServiceTicketsID',
'JobID',
'Ticket Number',
'Reason for Visit',
'Warranty/VPO',
'Date Ticket Received',
'Date of Service',
'Service Person'
])
As well as the remaining code affiliated with it, the program runs correctly. The frame is cleared out and the new TreeView is brought in, as well as its headers.
As I said, I am brand new to programming and as such am new to using StackOverflow. With that said, I apologize if I've not provided enough information, posted incorrectly, etc. I also apologize in advance for any sloppiness you may find in the code lol.
I appreciate all input.
JobDF = pd.DataFrame(treevar, index = [0])
and
cursor1 = self.cursor.execute("SELECT * from 'Service Tickets' WHERE JobID = ?", (self.JobID))
were the culprits.
It should have been
JobDF = pd.DataFrame(treevar) #removed the index argument
and
cursor1 = self.cursor.execute("SELECT * from 'Service Tickets' WHERE JobID = ?", (self.JobID,)) #added a comma (self.JobID,))
I've taken the below code from another source - it is not my own code.
The code allows you to select a cell in the data table, and the 'downloads' data for that cell will chart based on the row of the cell selected.
How do I expand this code such that if I have multiple variables (eg. 'downloads' and 'uploads') and so more columns in the data table, I can chart data based on that cell (so where row AND column are important)? Alternatively, how can I define as a variable the column number of a selected cell (in the same way selected_row below can be used to define the row number)?
from datetime import date
from random import randint
from bokeh.models import ColumnDataSource, Column
from bokeh.plotting import figure, curdoc
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn, Div
import numpy as np
data = dict(dates = [date(2014, 3, i + 1) for i in range(10)],
downloads = [randint(0, 100) for i in range(10)])
d_source = ColumnDataSource(data)
columns = [TableColumn(field = "dates", title = "Date", formatter = DateFormatter()),
TableColumn(field = "downloads", title = "Downloads")]
data_table = DataTable(source = d_source, columns = columns, width = 400, height = 280)
def table_select_callback(attr, old, new):
selected_row = new[0]
download_count = data['downloads'][selected_row]
chart_data = np.random.uniform(0, 100, size = download_count)
p = figure(title = 'bla')
r = p.line(x = range(len(chart_data)), y = chart_data)
root_layout.children[1] = p
d_source.selected.on_change('indices', table_select_callback)
root_layout = Column(data_table, Div(text = 'Select Date'))
curdoc().add_root(root_layout)
This is the final working code (run from command line with bokeh serve --show app.py):
from datetime import date
from random import randint
from bokeh.models import ColumnDataSource, Column, TableColumn, DateFormatter, DataTable, CustomJS
from bokeh.plotting import figure, curdoc
source = ColumnDataSource(dict(dates = [date(2014, 3, i + 1) for i in range(10)], downloads = [randint(0, 100) for i in range(10)]))
columns = [TableColumn(field = "dates", title = "Date", formatter = DateFormatter()), TableColumn(field = "downloads", title = "Downloads")]
data_table = DataTable(source = source, columns = columns, width = 400, height = 280, editable = True, reorderable = False)
info_source = ColumnDataSource(dict(row = [], column = []))
source_code = """
var grid = document.getElementsByClassName('grid-canvas')[0].children;
var row, column = '';
for (var i = 0,max = grid.length; i < max; i++){
if (grid[i].outerHTML.includes('active')){
row = i;
for (var j = 0, jmax = grid[i].children.length; j < jmax; j++)
if(grid[i].children[j].outerHTML.includes('active')) {
column = j;
source2.data = {row: [row], column: [column]};
}
}
}"""
callback = CustomJS(args = dict(source = source, source2 = info_source), code = source_code)
source.selected.js_on_change('indices', callback)
def py_callback(attr, old, new):
source.selected.update(indices = [])
print(info_source.data)
source.selected.on_change('indices', py_callback)
curdoc().add_root(Column(data_table))
My suggestion is to use my another post that uses a JS callback to access the row and column of the selected cell. This must be a JS callback as it uses HTML elements to walk through. So the steps are as follows:
Define a new ColumnDataSource that will contain the row and column number of a clicked cell
info_source = ColumnDataSource(dict(row = [], column = []))
Use the JS callback from this post to fill in the row and column values in this new table_info_source like this:
callback=CustomJS(args=dict(source=d_source,source2=info_source),code=source_code)
source.selected.js_on_change('indices', callback)
Inside the JS callback store the row and column index like this:
source2.data = {row:[row],column:[column]};
Access the info_source.data information in your Python callback to draw a plot
print (info_source.data)
Both callback are attached to the same source but usually JS callback is executed first so the data should be available in the Python callback on time. Having the index of row and column of the clicked cell you should be able to retrieve the required data and draw your chart.
I want to use a checkbox to control the ratio multiplied in slider function.
First I try to change the variable directly, but failed.
Then I try to change the dragCommand, but also failed.
How can I control it?
import pymel.core as pm
import math
myRatio = math.sqrt(2) * 0.5
def myPolyBevel(*args):
# called by convert
def convertOn(*args):
#myRatio = math.sqrt(2) * 0.5
myOffsetSlider.dragCommand = myOffsetOn
def convertOff(*args):
#myRatio = 1.0
myOffsetSlider.dragCommand = myOffsetOff
# called by offset
def myOffsetOn(*args):
temp = pm.floatSliderGrp( myOffsetSlider, query = True, value = True ) * myRatio
pm.setAttr( myBevel.name()+".offset", temp )
def myOffsetOff(*args):
temp = pm.floatSliderGrp( myOffsetSlider, query = True, value = True )
pm.setAttr( myBevel.name()+".offset", temp )
# main
if pm.selected():
# add Bevel
newBevel = pm.polyBevel3( pm.selected(), offset = 0.1 * myRatio, segments = 2, smoothingAngle = 30, chamfer = 1 )
myBevel = newBevel[0]
# UI
bevelWindow = pm.window(title = 'Bevel')
bevelLayout = pm.columnLayout()
myConvert = pm.checkBoxGrp( numberOfCheckBoxes = 1, label = '', label1 = 'Convert', value1 = 1, onCommand = convertOn, offCommand = convertOff )
myOffsetSlider = pm.floatSliderGrp( label='Offset', field = True,
minValue = 0.0, maxValue = 5.0,
fieldMinValue = 0.0, fieldMaxValue = 100.0,
value = 0.1, step = 0.001,
dragCommand = myOffsetOn, changeCommand = myOffsetOn )
pm.showWindow()
# Main
mainWindow = pm.window(title = 'Star')
mainLayout = pm.gridLayout( cellWidthHeight = (40,40), numberOfColumns = 5 )
bevelButton = pm.button( label = 'Bevel', command = myPolyBevel)
pm.showWindow()
You may have to not nest all this command, it makes it harder (or use some Class method)
use partial to pass args :
Maya Python - Using data from UI
here a useful post you can refer, check theodor and my answers on the topic (we often answer this question )
I am new to python and recently i make dictionary using Python and Sqlite3 with tkinter.
When I run the code it returns multiple line in IDLE but in the GUI its only display the last result. I would like to display all the information in the GUI. Thanks you for any help and suggestion.
import tkinter
import sqlite3
class Dictionary:
def __init__(self,master =None):
self.main_window = tkinter.Tk()
self.main_window.title("Lai Mirang Dictionary")
self.main_window.minsize( 600,400)
self.main_window.configure(background = 'paleturquoise')
self.frame1 = tkinter.Frame()
self.frame2= tkinter.Frame(bg = 'red')
self.frame3 =tkinter.Text( foreground = 'green')
self.frame4 = tkinter.Text()
self.lai_label = tkinter.Label(self.frame1,anchor ='nw',font = 'Times:12', text = 'Lai',width =25,borderwidth ='3',fg='blue')
self.mirang_label = tkinter.Label(self.frame1,anchor ='ne',font = 'Times:12', text = 'Mirang',borderwidth ='3',fg ='blue')
self.lai_label.pack(side='left')
self.mirang_label.pack(side = 'left')
self.kawl_buttom= tkinter.Button(self.frame2 ,fg = 'red',font = 'Times:12',text ='Kawl',command=self.dic,borderwidth ='3',)
self.lai_entry = tkinter.Entry(self.frame2, width= 28, borderwidth ='3',)
self.lai_entry.focus_force()
self.lai_entry.bind('<Return>', self.dic,)
self.lai_entry.configure(background = 'khaki')
self.lai_entry.pack(side='left')
self.kawl_buttom.pack(side = 'left')
self.value = tkinter.StringVar()
self.mirang_label= tkinter.Label(self.frame3,font = 'Times:12',fg = 'blue',textvariable = self.value,justify = 'left',wraplength ='260',width = 30, height = 15,anchor = 'nw')
self.mirang_label.pack()
self.mirang_label.configure(background = 'seashell')
self.copyright_label = tkinter.Label(self.frame4,anchor ='nw',font = 'Times:12:bold',text = "copyright # cchristoe#gmail.com",width = 30,borderwidth = 3, fg = 'purple',)
self.copyright_label.pack()
self.frame1.pack()
self.frame2.pack()
self.frame3.pack()
self.frame4.pack()
tkinter.mainloop()
self.main_window.quit()
def dic(self, event = None):
conn = sqlite3.connect('C:/users/christoe/documents/sqlite/laimirangdictionary.sqlite')
c = conn.cursor()
kawl = self.lai_entry.get()
kawl = kawl + '%'
c.execute("SELECT * FROM laimirang WHERE lai LIKE ?", (kawl,))
c.fetchall
for member in c:
out = (member)
self.value.set(out)
print(out, )
dic=Dictionary()
You need to change:
c.execute("SELECT * FROM laimirang WHERE lai LIKE ?", (kawl,))
c.fetchall
for member in c:
out = (member)
self.value.set(out)
print(out, )
To:
for member in c.execute("SELECT * FROM laimirang WHERE lai LIKE ?", (kawl,)):
current_text = self.value.get()
new_text = current_text +( "\n" if current_text else "") +" ".join(member)
self.value.set(new_text)
The new version gets the current value of the StringVar value and then appends the results returned with a space inbetween for each row returned with each row on its own line. What you were doing however involved just updating the StringVar to be the current member object, and therefore it only ever had the last values.
This is how it looks with more than one line: