如何根据csv文件条目的数量动态创建tkinter按钮

时间:2018-11-07 00:55:57

标签: python csv tkinter

我正在制作一个将文本自动添加到剪贴板的应用程序。为了使它更具动态性,我尝试将复制的文本保存在CSV文件中。到目前为止,我已经设法使CSV文件导入并从中提取数据,但是当我尝试将测试添加到剪贴板时,我仅从最后一个按钮中获取了文本。

这是我的CSV文件(script.csv)

function table($hour, $row) {
    global $rs;
    // if $rs is null then query database (this should be executed only once - first time)
    if ($rs === null) 
    {
        // first column of the query is used as key in returned array
        $rs = sqlQuery("select concat(t.tbl_row,'_',t.tbl_col) as pos, t.tbl_id, t.sub_id, s.sub_name
                        from redips_timetable t, redips_subject s
                        where t.sub_id = s.sub_id", 0);
    }
    print '<tr>';
    print '<td class="mark dark">' . $hour . '</td>';
    // column loop starts from 1 because column 0 is for hours
    for ($col = 1; $col <= 5; $col++) {
        // create table cell
        print '<td>';
        // prepare position key in the same way as the array key looks
        $pos = $row . '_' . $col;
        // if content for the current table cell exists
        if (array_key_exists($pos, $rs)) {
            // prepare elements for defined position (it can be more than one element per table cell)
            $elements = $rs[$pos];
            // id of DIV element will start with sub_id and followed with 'b' (because cloned elements on the page have 'c') and with tbl_id
            // this way content from the database will not be in collision with new content dragged from the left table and each id stays unique
            $id = $elements[2] . 'b' . $elements[1];
            $name = $elements[3];
            $class = substr($id, 0, 2); // class name is only first 2 letters from ID
            print "<div id=\"$id\" class=\"redips-drag $class\">$name</div>";

        }
        // close table cell
        print '</td>';
    }
    print "</tr>\n";
}

然后这是我的python程序

idnum,name,script
0,testone,This is a test
1,testtwo,I hope it works
2,testthree,This better work
3,testfour,Please work

1 个答案:

答案 0 :(得分:0)

lambda函数将计算表达式script[i],并且i是最后一个idnum,由for循环设置,该表达式的计算结果为:Please work。您必须确保将变量i作为常量传递:

command=lambda i=i: add_to_clipboard(script[i])

i=i是执行此操作的常用方法。